Swagger Swashbuckle Asp.NET Core:显示使用的每个枚举的详细信息

ijxebb2r  于 2023-06-22  发布在  .NET
关注(0)|答案(2)|浏览(205)

我有以下枚举:

public enum TicketQuestionType
{
    General = 1,
    Billing = 2,
    TMS = 3,
    HOS = 4,
    DeviceManagement = 5
}

模型类:

public class TicketCreateApi
{
    public string Subject { get; set; }
    public TicketQuestionType QuestionType { get; set; } = TicketQuestionType.General;
    public TicketType Type { get; set; } = TicketType.Problem;
    public TicketStatus Status { get; set; } = TicketStatus.New;
    public TicketPriority Priority { get; set; } = TicketPriority.Normal;
    public string Description { get; set; }
    public List<string> Attachments { get; set; }
    public int? DeviceId { get; set; }
    public int? DriverId { get; set; }
}

我的API方法使用它:

Task<IActionResult> Create(TicketCreateApi model);

Swagger生成以下内容:

还有这个

因此,我们只能看到默认值,而无法看到可用枚举列表(名称和值)。我想展示一下。怎么做?

ojsjcaue

ojsjcaue1#

我们只能看到默认值,没有办法看到可用的枚举列表(名称和值)。我想展示一下。怎么做?
要以swagger的字符串形式显示枚举,您可以配置JsonStringEnumConverter,并在ConfigureServices中添加以下行:

services.AddControllers().AddJsonOptions(options =>
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

输出如下:

如果希望将枚举显示为stings和int值,可以尝试创建EnumSchemaFilter来更改模式。代码如下:

public class EnumSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema model, SchemaFilterContext context)
    {
        if (context.Type.IsEnum)
        {
            model.Enum.Clear();
            Enum.GetNames(context.Type)
                .ToList()
                .ForEach(name => model.Enum.Add(new OpenApiString($"{Convert.ToInt64(Enum.Parse(context.Type, name))} = {name}")));
        }
    }
}

将SwaggerGen配置为在ShemaFilter上方使用。

services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo
            {
                Version = "v1",
                Title = "ToDo API",
                Description = "A simple example ASP.NET Core Web API",
                TermsOfService = new Uri("https://example.com/terms"),
                Contact = new OpenApiContact
                {
                    Name = "Shayne Boyer",
                    Email = string.Empty,
                    Url = new Uri("https://twitter.com/spboyer"),
                },
                License = new OpenApiLicense
                {
                    Name = "Use under LICX",
                    Url = new Uri("https://example.com/license"),
                }
            });
              
            c.SchemaFilter<EnumSchemaFilter>();
        });

结果是这样的:

4si2a6ki

4si2a6ki2#

我试过EnumSchemaFilter。我每次提交请求时都有错误。因为将枚举字符串序列化为int
我用了这个代码块,我希望它能工作

services.AddControllersWithViews()
                    .AddJsonOptions(
                        opts =>
                        {
                            var enumConverter = new JsonStringEnumConverter();
                            opts.JsonSerializerOptions.Converters.Add(enumConverter);
                        });

相关问题