Home > Mobile >  Can you override Swagger's format for a class / struct
Can you override Swagger's format for a class / struct

Time:07-22

I'm using Swagger with an Asp.Net Core web api project but having issues with DateOnly items in the body of an API request.

The model used for the API is

public record Meeting(
    DateOnly MeetingDate,
    string Agenda);

I have written a JsonConverter that is included in the options for Asp.Net so the DateOnly is serialized to / from ISO-8601 calendar date format, i.e. yyyy-MM-dd.

The problem is that Swagger's examples in swagger-ui for DateOnly properties appear as

"meetingDate": {
        "year": 0,
        "month": 0,
        "day": 0
      }

Is there a way to tell Swagger to use ISO-8601 format when documenting DateOnly properties?

For clarification, the API works if ISO-8601 format is passed through Swagger but if you use Swagger's example, it fails.

CodePudding user response:

you can map the DateOnly datatype to string like this.

builder.Services.AddSwaggerGen(c=>
{
   c.MapType<DateOnly>(() => new OpenApiSchema { Type = "string", Format = "date" });
});
  • Related