首页 > 解决方案 > 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]));
            }
        }
    }

但是这里的问题是,当我想在获取请求中尝试该枚举时,我看到以下选项: 在此处输入图像描述

有没有办法将其更改为仅在用户想要选择时显示枚举整数值?

标签: enumsswashbuckle.aspnetcore

解决方案


我可以通过定义自定义 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>();
        }
    }
}

推荐阅读