//首先startup注入 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo() { Title = "App", Version = "v1" }); var xmlFile = $"App.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.DocumentFilter<HiddenApiFilter>();//过滤的核心filter foreach (var name in Directory.GetFiles(AppContext.BaseDirectory, "*.xml", SearchOption.AllDirectories)) { c.IncludeXmlComments(name); } });
/// <summary> /// 隐藏接口,不生成到swagger文档展示(Swashbuckle.AspNetCore 5.0.0) /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public partial class HiddenApiAttribute : Attribute { } public class HiddenApiFilter : IDocumentFilter { /// <summary> /// 重写Apply方法,移除隐藏接口的生成 /// </summary> /// <param name="swaggerDoc">swagger文档文件</param> /// <param name="context"></param> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { foreach (ApiDescription apiDescription in context.ApiDescriptions) { var api = apiDescription.ActionDescriptor as Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor; //这里强转来获取到控制器的名称 var contoller = api.ControllerName; if (api.ControllerName== "CommonBase")//过滤的核心逻辑 { string key = "/" + apiDescription.RelativePath; if (key.Contains("?")) { int idx = key.IndexOf("?", StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.Paths.Remove(key); } } } }