Ole*_* Sh 15 asp.net-web-api swagger swashbuckle asp.net-core swashbuckle.aspnetcore
我有以下枚举:
public enum TicketQuestionType
{
General = 1,
Billing = 2,
TMS = 3,
HOS = 4,
DeviceManagement = 5
}
Run Code Online (Sandbox Code Playgroud)
和模型类:
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; }
}
Run Code Online (Sandbox Code Playgroud)
我的 API 方法使用它:
Task<IActionResult> Create(TicketCreateApi model);
Run Code Online (Sandbox Code Playgroud)
Swagger 生成以下内容:
和这个:
因此,我们只能看到默认值,而无法查看可用的枚举列表(名称和值)。我想展示一下。怎么做?
Zhi*_* Lv 37
我们只能看到默认值,无法看到可用的枚举列表(名称和值)。我想展示一下。怎么做?
要将枚举显示为 swagger 中的字符串,您可以配置 JsonStringEnumConverter,在 ConfigureServices 中添加以下行:
services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
Run Code Online (Sandbox Code Playgroud)
输出如下:
如果您想将枚举显示为字符串和 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}")));
}
}
}
Run Code Online (Sandbox Code Playgroud)
配置 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>();
});
Run Code Online (Sandbox Code Playgroud)
结果是这样的:
| 归档时间: |
|
| 查看次数: |
14752 次 |
| 最近记录: |