我创建了一个Swagger架构过滤器,如下所示:
public class OpenApiIgnoreEnumSchemaFilter : ISchemaFilter
{
private readonly bool _useNames;
public OpenApiIgnoreEnumSchemaFilter(bool useNames = false)
{
_useNames = useNames;
}
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if (!context.Type.IsEnum && !(Nullable.GetUnderlyingType(context.Type)?.IsEnum ?? false))
{
return;
}
Type type = (context.Type.IsEnum ? context.Type : Nullable.GetUnderlyingType(context.Type));
List<IOpenApiAny> list = new List<IOpenApiAny>();
string[] names = Enum.GetNames(type);
int[] values = Enum.GetValues(type).Cast<int>().ToArray();
foreach (var (text, value) in names.Select((string name, int index) => (name, values[index])).ToList())
{
if (!type.GetMember(text)[0].GetCustomAttributes<OpenApiIgnoreEnumAttribute>().Any())
{
IOpenApiAny item;
if (!_useNames)
{
IOpenApiAny openApiAny = new OpenApiInteger(value);
item = openApiAny;
}
else
{
IOpenApiAny openApiAny = new OpenApiString(text);
item = openApiAny;
}
list.Add(item);
}
}
schema.Enum = list;
}
}
它在一定程度上工作得很好--如果我将构造函数参数中的true
值传递给它,并try 从浏览器中SwaggerUI的下拉列表中 Select 一个值,它会告诉我只允许整数值:
有没有办法让模式过滤器提供的功能(字符串化的枚举名称+隐藏一些我想要隐藏的成员),同时能够在UI中使用这些字符串化的枚举?