Enums Swashbuckle中的自定义SchemaFilter显示带有说明的枚举,但更改输入值
我需要在swagger中为请求的模式添加枚举描述,因此我定义了此筛选器:Enums Swashbuckle中的自定义SchemaFilter显示带有说明的枚举,但更改输入值,enums,swashbuckle.aspnetcore,Enums,Swashbuckle.aspnetcore,我需要在swagger中为请求的模式添加枚举描述,因此我定义了此筛选器: public class EnumSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema model, SchemaFilterContext context) { if (context.Type.IsEnum) { model.En
public class EnumSchemaFilter : ISchemaFilter
{
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();
var names = Enum.GetNames(context.Type);
names
.ToList()
.ForEach(n => model.Enum.Add(new OpenApiString($"{n} : {(int)Enum.Parse(context.Type, n)}")));
model.Example = new OpenApiInteger((int)Enum.Parse(context.Type, names[0]));
}
}
}
但是,这里的问题是,当我想在get请求中尝试该枚举时,我会看到以下选项:
是否有办法将此更改为仅在用户想要选择时显示枚举整数值?我可以通过定义自定义参数过滤器来解决此问题:
public class SchemaParametersFilter : IParameterFilter
{
public void Apply(OpenApiParameter parameter, ParameterFilterContext context)
{
var type = context.ParameterInfo?.ParameterType;
if (type == null)
return;
if (type.IsEnum && parameter.In == ParameterLocation.Query)
{
var names = Enum.GetNames(type);
parameter.Schema.Enum = names.OfType<string>().Select(p => new OpenApiInteger((int)Enum.Parse(type, p))).ToList<IOpenApiAny>();
}
}
}
公共类SchemaParametersFilter:IPParameterFilter
{
public void Apply(openapipParameter参数、ParameterFilterContext上下文)
{
变量类型=context.ParameterInfo?.ParameterType;
if(type==null)
返回;
if(type.IsEnum&¶meter.In==ParameterLocation.Query)
{
var name=Enum.GetNames(类型);
parameter.Schema.Enum=names.OfType();
}
}
}