Search code examples
asp.netswaggerswashbuckle

Swashbuckle use format identifier via XML comment in .NET application


I'm trying to get the format identifier printed on the Swagger UI which is stated on their homepage. In the auto-generated json file it should look like in this example:
format property example

The way of how I'd like to achieve that is via xml comments in my view model class. This works well for tags like example, summary etc., but there is no tag like format. It would be important for me to state that the string we are awaiting here in the API must be in a certain format.

A similar question has been asked here, but there hasn't been an answer for the format identifier.

How can I achieve this? Versions used: .NET 7 and Swashbuckle v 6.4.0.

My view model looks like that:

public class MeasurementViewModel {
    /// <example>20.01.2003</example>
    /// <format>dd.mm.yyyy</format>  <-- this is what I would expect but doesn't have any effect
    [JsonProperty("patient_birthdate")] public string? PatientDateOfBirth { get; set; }
}

Solution

  • Found a solution thanks to that answer.

    I added the additional package "Swashbuckle.AspNetCore.Annotations" via NuGet and in my Startup.cs where I configure the Swagger generation I enable the annotations:

    services.AddSwaggerGen(c =>
        ...
        c.EnableAnnotations();
    }
    

    In my ViewModel I can now use the following annotation:

    /// <example>20.01.2002</example>
    [JsonProperty("patient_birthdate"), SwaggerSchema(Format = "dd.mm.yyyy")] public string? PatientDateOfBirth { get; set; }
    

    .. which results in a beautiful documentation:

    enter image description here