Using ASP.NET Core-6 Web API for a payment project, I have these fields:
public string ReferenceNumber { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
By default on swagger, the date fields are displayed as:
{
"referenceNumber": "string",
"startDate": "2022-09-01T02:25:20.619Z",
"endDate": "2022-09-01T02:25:20.619Z"
}
On Swagger, how do I make it display the default format for StartDate and EndDate as:
{
"referenceNumber": "string",
"startDate": "YYYY-MM-DD",
"endDate": "YYYY-MM-DD"
}
Thanks
CodePudding user response:
If you want to give a format to DateTime, your DateTime properties have to be a string.
You can generate Swagger example requests and responses with Swashbuckle. "Swashbuckle.AspNetCore.Filters"
It will help you to create your own request and response samples, something like this.
public class Example
{
public string ReferenceNumber { get; set; }
public string StartDate { get; set; }
public string EndDate { get; set; }
}
your request Sample:
public class SampleRequest : IExamplesProvider <Example>
{
public Example GetExamples()
{
return new Example
{
ReferenceNumber = "REF001",
StartDate = DateTime.Now.ToString("d"),
EndDate = DateTime.Now.ToString("d")
};
}
}
How you will see it on swagger:
CodePudding user response:
So you can do it using Newtonsoft and set a default format for all dates. Here's a sample code
services.AddControllers()
.AddNewtonsoftJson(options =>
{
var dateConverter = new Newtonsoft.Json.Converters.IsoDateTimeConverter
{
DateTimeFormat = "YYYY-MM-DD"
};
});