Swagger 将小数显示为 0.00 而不是 0

问题描述 投票:0回答:1

我有这门课:

public class CostDto
{
    public int Id{ get; set; }
    public decimal? Price { get; set; }
}

大摇大摆地表明了这一点:

{
    "Id": 0,
    "Price": 0
}

我更喜欢这个:

{
    "Id": 0,
    "Price": 0.00
}

这将更清楚地向用户表明

Price
的返回值是十进制类型,而不是整数类型。这有可能大摇大摆吗? 我发现一些帖子提到了类似的内容,但它似乎不起作用:

services.AddSwaggerGen(options =>
{
    options.MapType<decimal>(() => new OpenApiSchema { Type = "number", Format = "decimal" });
    options.MapType<decimal?>(() => new OpenApiSchema { Type = "number", Format = "decimal", Nullable = true });
});
c# .net swagger swagger-ui
1个回答
0
投票

你可以试试这个:

public class DecimalSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema.Type == "number" && schema.Format == "decimal")
        {
            schema.Example = OpenApiAnyFactory.CreateFor(schema, "0.00");
        }
    }
}

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 });
});
© www.soinside.com 2019 - 2024. All rights reserved.