swagger添加枚举注释

第一步,添加swagger过滤器

 1 public class EnumSchemaFilter : ISchemaFilter
 2     {
 3         public void Apply(OpenApiSchema model, SchemaFilterContext context)
 4         {
 5             if (context.Type.IsEnum)
 6             {
 7                 StringBuilder stringBuilder = new StringBuilder();
 8                 Enum.GetNames(context.Type)
 9                     .ToList()
10                     .ForEach(name =>
11                     {
12                         Enum e = (Enum)Enum.Parse(context.Type, name);
13                         var data = $"{name}({e.GetDesc()})={Convert.ToInt64(Enum.Parse(context.Type, name))}";
14 
15                         stringBuilder.AppendLine(data);
16                     });
17                 model.Description = stringBuilder.ToString();
18 
19 
20                 model.Type = context.Type.Name;
21                 model.Format = context.Type.Name;
22             }
23         }
24         
25     }
26 
27 public static class EnumExtensions
28     {
29         /// <summary>
30         /// 获取枚举信息(枚举名称、描述、值)
31         /// </summary>
32         /// <param name="value"></param>
33         /// <returns></returns>
34         public static string GetEnumDesc(this Enum value)
35         {
36             var type=value.GetType();
37             var names = Enum.GetNames(type).ToList();
38 
39             FieldInfo[] fields = type.GetFields();
40             foreach (FieldInfo item in fields)
41             {
42                 if (!names.Contains(item.Name))
43                 {
44                     continue;
45                 }
46                 if (value.ToString() != item.Name)
47                 {
48                     continue;
49                 }
50                 DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])item.
51             GetCustomAttributes(typeof(DescriptionAttribute), false);
52                 if (EnumAttributes.Length > 0)
53                 {
54                     return EnumAttributes[0].Description;
55                 }
56                 else
57                 {
58                     return "";
59                 }
60             }
61 
62             return "";
63         }
64     }
View Code

 

  第二步,注入

 1 public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddControllers();
 4             services.AddSwaggerGen(c =>
 5             {
 6                 c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplication2", Version = "v1" });
 7 
 8                 c.SchemaFilter<EnumSchemaFilter>();
 9             });
10         }
View Code

 

posted @ 2023-02-25 10:25  a2151888  阅读(206)  评论(0编辑  收藏  举报