我正在使用.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"
}
型
1条答案
按热度按时间at0kjp5o1#
MinimalApi和Swashbuckle Swagger之间存在一个问题,您必须在两个不同的地方设置该选项:
字符串
有关此问题的更多信息:https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/2293