如何在最小API端点和Swagger中使枚举序列化默认为字符串?

sh7euo9m  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(119)

我正在使用.NET最小API,并且遇到了枚举的JSON序列化/反序列化行为的问题。尽管我尝试改变使用字符串而不是整数的行为,但Swashbuckle.AspNetCore的Swagger文档仍然将枚举表示为整数。

using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);

// Docs: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-7.0#configure-json-deserialization-options-globally
builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapPost("/api/v1/test", (TestRequest request) => Results.Ok(request));

app.Run();

public enum GridType
{
    Arithmetic,
    Geometric
}

public class TestRequest
{
    public required string Name { get; init; }
    public required GridType Type { get; set; }
}

字符串
但是当Swagger UI打开时,我仍然会得到一个枚举的整数:

{
  "name": "string",
  "type": 0
}


预期输出为:

{
  "name": "string",
  "type": "Arithmetic"
}

at0kjp5o

at0kjp5o1#

MinimalApi和Swashbuckle Swagger之间存在一个问题,您必须在两个不同的地方设置该选项:

builder.Services.ConfigureHttpJsonOptions(options =>
{
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
    options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});

字符串
有关此问题的更多信息:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2293

相关问题