/// <summary> /// SwaggerIgnoreAttribute /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method|AttributeTargets.Field|AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class SwaggerIgnoreAttribute : Attribute, IFilterMetadata { /// <summary> /// construct /// </summary> /// <param name="ignore"></param> public SwaggerIgnoreAttribute(bool ignore = true) { IgnoreApi = ignore; } /// <summary> /// /// </summary> public string GroupName { get; set; } /// <summary> /// /// </summary> public bool IgnoreApi { get; set; } }
/// <summary> /// SwaggerIgnoreFilter /// </summary> public class SwaggerIgnoreFilter : Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var ignoreApis = context.ApiDescriptions.Where(o => { if (o.TryGetMethodInfo(out MethodInfo methodInfo)) { if (methodInfo == null) return false; if (methodInfo.CustomAttributes.Any(any => any.AttributeType == typeof(SwaggerIgnoreAttribute))) { var attribute = methodInfo.GetCustomAttribute<SwaggerIgnoreAttribute>(); return attribute?.IgnoreApi ?? false; } else if (methodInfo.DeclaringType?.CustomAttributes.Any(any => any.AttributeType == typeof(SwaggerIgnoreAttribute)) ?? false) { var attribute = methodInfo.DeclaringType.GetCustomAttribute<SwaggerIgnoreAttribute>(); return attribute?.IgnoreApi ?? false; } return false; } return false; }).ToList(); if (ignoreApis.Count > 0) { foreach (var ignoreApi in ignoreApis) { swaggerDoc.Paths.Remove("/" + ignoreApi.RelativePath); } } } }
services.AddSwaggerGen( options => { options.DocumentFilter<SwaggerIgnoreFilter>(); });
标签:return,attribute,SwaggerIgnore,SwaggerIgnoreAttribute,methodInfo,false,public From: https://www.cnblogs.com/dayang12525/p/17264832.html