dotnet core 2.2開發項目中,常會使用Swagger UI來生成在線Api文檔。api
/// <summary> /// 隱藏swagger接口特性標識 /// </summary> [System.AttributeUsage(System.AttributeTargets.Method | System.AttributeTargets.Class)] public partial class HiddenApiAttribute : System.Attribute { } /// <summary> /// 隱藏接口,不生成到swagger文檔展現 /// </summary> public class HiddenApiFilter : IDocumentFilter { /// <summary> /// 過濾器 /// </summary> /// <param name="swaggerDoc"></param> /// <param name="context"></param> public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { foreach (ApiDescription apiDescription in context.ApiDescriptions) { if (apiDescription.TryGetMethodInfo(out MethodInfo method)) { if (method.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute)) || method.CustomAttributes.Any(t => t.AttributeType == typeof(HiddenApiAttribute))) { string key = "/" + apiDescription.RelativePath; if (key.Contains("?")) { int idx = key.IndexOf("?", System.StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.Paths.Remove(key); } } } } }
注意:他不能隱藏一個Controller中的某個Method,好比僅隱藏Post或Get方法,由於它是對路由Paths.Removespa
Starts.cs中加入代碼:blog
c.DocumentFilter<HiddenApiFilter>();
Controller類或某個方法加入代碼:接口
[HiddenApi] public class ValuesController : ControllerBase { ... }
/// <summary> /// Add enum value descriptions to Swagger /// </summary> public class EnumDocumentFilter : IDocumentFilter { /// <inheritdoc /> public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { // add enum descriptions to result models foreach (var schemaDictionaryItem in swaggerDoc.Definitions) { var schema = schemaDictionaryItem.Value; foreach (var propertyDictionaryItem in schema.Properties) { var property = propertyDictionaryItem.Value; var propertyEnums = property.Enum; if (propertyEnums != null && propertyEnums.Count > 0) { property.Description += DescribeEnum(propertyEnums); } } } } private static string DescribeEnum(IEnumerable<object> enums) { var enumDescriptions = new List<string>(); Type type = null; foreach (var enumOption in enums) { if (type == null) type = enumOption.GetType(); enumDescriptions.Add($"{Convert.ChangeType(enumOption, type.GetEnumUnderlyingType())} = {Enum.GetName(type, enumOption)},{GetDescription(type, enumOption)}"); } return $"{Environment.NewLine}{string.Join(Environment.NewLine, enumDescriptions)}"; } public 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; } }
Starts.cs中加入代碼:ip
c.DocumentFilter<EnumDocumentFilter>();
以上。路由