enums - Swashbuckle 中的自定义 SchemaFilter 以显示带有描述的枚举但更改输入值
问题描述
我需要在 swagger 中为请求的模式添加枚举描述,所以我定义了这个过滤器:
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]));
}
}
}
但是这里的问题是,当我想在获取请求中尝试该枚举时,我看到以下选项:
有没有办法将其更改为仅在用户想要选择时显示枚举整数值?
解决方案
我可以通过定义自定义 ParametersFilter 来解决这个问题:
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>();
}
}
}
推荐阅读
- java - Logstash 升级版本后无法运行实例
- c++ - Bash 脚本无法从 C++ 代码正常运行
- c - Makefile 过滤只是...不起作用?
- c# - 未处理的异常。无法归档或组装“系统内存”
- javascript - Chrome 扩展清单 v3 和内联脚本
- python - 尽管在python中显示十进制值,但显示唯一计数
- tkinter - 错误,在使用 iconbitmap tkinter.TclError: bitmap "image\inventory.ico" 未定义
- javascript - 如何在 React Grid 布局中为 WidthProvider 赋予特定的宽度值
- node.js - 每个 Node.js 发送令牌 CSRF Laravel - 错误 CSRF 令牌不匹配
- vb.net - 如何在 VB.NET 中专门化模板/泛型?