.net Core6 swagger 枚举注释
public class EnumSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema model, SchemaFilterContext context) { if (context.Type.IsEnum) { StringBuilder stringBuilder = new StringBuilder(); Enum.GetNames(context.Type) .ToList() .ForEach(name => { Enum e = (Enum)Enum.Parse(context.Type, name); var data = $"{name}({e.GetDesc()})={Convert.ToInt64(Enum.Parse(context.Type, name))}"; stringBuilder.AppendLine(data); }); model.Description = stringBuilder.ToString(); model.Type = context.Type.Name; model.Format = context.Type.Name; } } } public static class EnumExtensions { /// <summary> /// 获取枚举信息(枚举名称、描述、值) /// </summary> /// <param name="value"></param> /// <returns></returns> public static string GetEnumDesc(this Enum value) { var type=value.GetType(); var names = Enum.GetNames(type).ToList(); FieldInfo[] fields = type.GetFields(); foreach (FieldInfo item in fields) { if (!names.Contains(item.Name)) { continue; } if (value.ToString() != item.Name) { continue; } DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])item. GetCustomAttributes(typeof(DescriptionAttribute), false); if (EnumAttributes.Length > 0) { return EnumAttributes[0].Description; } else { return ""; } } return ""; } }
注入
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication2", Version = "v1" }); //注入 c.SchemaFilter<EnumSchemaFilter>(); }); }