I have this class:
public class CostDto
{
public int Id{ get; set; }
public decimal? Price { get; set; }
}
In the swagger it shows this:
{
"Id": 0,
"Price": 0
}
And I would prefer this:
{
"Id": 0,
"Price": 0.00
}
This would more clearly indicate to the user that the returned value of Price
is of type decimal, not integer. It this possible at all in swagger?
I found some posts referring to something like this, but it doesn't seem to work:
services.AddSwaggerGen(options =>
{
options.MapType<decimal>(() => new OpenApiSchema { Type = "number", Format = "decimal" });
options.MapType<decimal?>(() => new OpenApiSchema { Type = "number", Format = "decimal", Nullable = true });
});
You could try this:
public class DecimalSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (schema.Type == "number" && schema.Format == "decimal")
{
schema.Example = OpenApiAnyFactory.CreateFromJson("0.01");
}
}
}
services.AddSwaggerGen(options =>
{
options.SchemaFilter<DecimalSchemaFilter>();
options.MapType<decimal>(() => new OpenApiSchema { Type = "number", Format = "decimal" });
options.MapType<decimal?>(() => new OpenApiSchema { Type = "number", Format = "decimal", Nullable = true });
});