只要在你的ConfigureServices中添加如下代码(两种方案都行)即可:
原创不易转载请注明转载地址,谢谢!
一、把枚举值改成枚举属性
//方法一
services.AddMvc(option => option.EnableEndpointRouting = false).AddJsonOptions(options =>{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
//方法二
services.AddControllers().AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
没改之前
改了之后
枚举
public enum UserType
{
/// <summary>
/// 超级管理员
/// </summary>
[Description("超级管理员")]
Administrator = 1,
/// <summary>
/// 高级管理员
/// </summary>
[Description("管理员")]
Admin = 2,
/// <summary>
/// 用户
/// </summary>
[Description("用户")]
User = 3
}
二、显示枚举描述
注意:里面的GetDescription方法时扩展方法,放在了后面
方法一:添加SwaggerEnumFilter类,继承IDocumentFilter,代码如下
using Microsoft.OpenApi.Any;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
namespace DotNetCoreApi.Filter
{
/// <summary>
/// swagger文档生成过滤器,用于枚举描述的生成
/// </summary>
public class SwaggerEnumFilter : IDocumentFilter
{
/// <summary>
/// 实现IDocumentFilter接口的Apply函数
/// </summary>
/// <param name="swaggerDoc"></param>
/// <param name="context"></param>
public void Apply(Microsoft.OpenApi.Models.OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
Dictionary<string, Type> dict = GetAllEnum();
foreach (var item in swaggerDoc.Components.Schemas)
{
var property = item.Value;
var typeName = item.Key;
Type itemType = null;
if (property.Enum != null && property.Enum.Count > 0)
{
if (dict.ContainsKey(typeName))
{
itemType = dict[typeName];
}
else
{
itemType = null;
}
List<OpenApiInteger> list = new List<OpenApiInteger>();
foreach (var val in property.Enum)
{
list.Add((OpenApiInteger)val);
}
property.Description += DescribeEnum(itemType, list);
}
}
}
private static Dictionary<string, Type> GetAllEnum()
{
Assembly ass = Assembly.Load("Model");//枚举所在的命名空间的xml文件名,我的枚举都放在Model层里(类库)
Type[] types = ass.GetTypes();
Dictionary<string, Type> dict = new Dictionary<string, Type>();
foreach (Type item in types)
{
if (item.IsEnum)
{
dict.Add(item.Name, item);
}
}
return dict;
}
private static string DescribeEnum(Type type, List<OpenApiInteger> 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);
if (string.IsNullOrEmpty(desc))
enumDescriptions.Add($"{item.Value.ToString()}:{Enum.GetName(type, value)};");
else
enumDescriptions.Add($"{item.Value.ToString()}:{Enum.GetName(type, value)},{desc};");
}
return $"<br><div>{Environment.NewLine}{string.Join("<br/>" + Environment.NewLine, enumDescriptions)}</div>";
}
private static string GetDescription(Type t, object value)
{
foreach (MemberInfo mInfo in t.GetMembers())
{
if (mInfo.Name == t.GetEnumName(value))
{
foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo))
{
if (attr.GetType() == typeof(DescriptionAttribute))
{
return ((DescriptionAttribute)attr).Description;
}
}
}
}
return string.Empty;
}
}
}
注册服务:在Startup中的ConfigureServices添加注册,如下
services.AddSwaggerGen(c =>
{
//省略其他代码
c.DocumentFilter<SwaggerEnumFilter>();
}
这种方法显示枚举描述如下
枚举如下
namespace Model.Enum
{
/// <summary>
/// 用户类型枚举
/// </summary>
public enum UserType
{
/// <summary>
/// 超级管理员
/// </summary>
[Description("超级管理员")]
Administrator = 1,
/// <summary>
/// 高级管理员
/// </summary>
[Description("管理员")]
Admin = 2,
/// <summary>
/// 用户
/// </summary>
[Description("用户")]
User = 3
}
}
方法二:添加EnumSchemaFilter 类,实现 ISchemaFilter 接口,代码如下:
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Util.Expand;
namespace DotNetCoreApi.Filter
{
/// <summary>
/// Swagger文档枚举字段显示枚举属性和枚举值,以及枚举描述
/// </summary>
public class EnumSchemaFilter : ISchemaFilter
{
/// <summary>
/// 实现接口
/// </summary>
/// <param name="model"></param>
/// <param name="context"></param>
public void Apply(OpenApiSchema model, SchemaFilterContext context)
{
if (context.Type.IsEnum)
{
model.Enum.Clear();
Enum.GetNames(context.Type)
.ToList()
.ForEach(name =>
{
Enum e = (Enum)Enum.Parse(context.Type, name);
model.Enum.Add(new OpenApiString($"{name}({e.GetDescription()})={Convert.ToInt64(Enum.Parse(context.Type, name))}"));
});
}
}
}
}
在Startup中的ConfigureServices添加注册,如下
services.AddSwaggerGen(c =>
{
//省略其他代码
c.SchemaFilter<EnumSchemaFilter>();
}
效果如下:
到此结束...