【Swagger】.NET Core 3.1 Swagger3.0枚举字段注释不显示的处理
前言
从Swagger2.0升级到Swagger3.0,发现枚举类型的注释不显示了。上网多方搜寻以后,发现好像没有官方的办法去解决,只能通过自身写适配Swagger的Filter去自行处理。
解决方法
方案大致通过以下几步来完成Filter
- 1、获取Model层所有枚举
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18/// <summary>
/// 获取Model层所有枚举
/// </summary>
/// <returns></returns>
private static Dictionary<string, Type> GetAllEnum()
{
var types = Assembly.Load("xxx.Models").GetTypes();
var dic = new Dictionary<string, Type>();
foreach (var item in types)
{
if (!item.IsEnum) continue;
if (!dic.ContainsKey(item.Name))
{
dic.Add(item.Name, item);
}
}
return dic;
} - 2、处理获取到的枚举
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18/// <summary>
/// 处理枚举
/// </summary>
/// <param name="type"></param>
/// <param name="enums"></param>
/// <returns></returns>
private static string DescribeEnum(Type type, List<OpenApiLong> enums)
{
var enumDescriptions = new List<string>();
foreach (var item in enums)
{
if (type == null) continue;
var value = Enum.Parse(type, item.Value.ToString());
var desc = GetDescription(type, value);
enumDescriptions.Add(string.IsNullOrEmpty(desc) ? $"{item.Value}": $"{item.Value} - {desc}");
}
return $"<br/>{Environment.NewLine}{string.Join("<br/>" + Environment.NewLine, enumDescriptions)}";
} - 3、处理过程中获取枚举的描述值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/// <summary>
/// 获取描述值
/// </summary>
private static string GetDescription(Type t, object value)
{
foreach (var info in t.GetMembers())
{
if (info.Name == t.GetEnumName(value))
{
foreach (var attr in Attribute.GetCustomAttributes(info))
{
if (attr.GetType() == typeof(DescriptionAttribute))
{
return ((DescriptionAttribute)attr).Description;
}
}
}
}
return string.Empty;
} - 4、继承Swashbuckle.AspNetCore.SwaggerGen下的IDocumentFilter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31public class EnumFilter : IDocumentFilter
{
public void Apply(Microsoft.OpenApi.Models.OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var dic = GetAllEnum();
foreach (var item in swaggerDoc.Components.Schemas)
{
var property = item.Value;
var typeName = item.Key;
if (property.Enum != null && property.Enum.Count > 0)
{
var itemType = dic.ContainsKey(typeName) ? dic[typeName] : null;
var list = new List<OpenApiLong>();
foreach (var val in property.Enum)
{
long value;
if (property.Format == "int32")
{
value = Convert.ToInt64(((OpenApiInteger)val).Value);
}
else
{
value = Convert.ToInt64(((OpenApiLong)val).Value);
}
list.Add(new OpenApiLong(value));
}
property.Description = DescribeEnum(itemType, list);
}
}
}
} - 5、注入Swagger的时候加进去最终只要通过在枚举上打上 [Description(“”)] 特性,就会得到各个枚举的注释。
1
2
3
4services.AddSwaggerGen(c =>{
// 通过Filter显示枚举描述
c.DocumentFilter<EnumFilter>();
});
具体效果如下:
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 CHUNGLAM!