背景
Swagger是目前最受歡迎的REST APIs文檔生成工具,同時也是API的在線測試工具。功能強大誰用誰知道。我就不用在這里推廣它了。今天要解決的問題是:如果讓一些特定的API接口在Swagger中不顯示,即從Swagger中過濾掉一些不想展示的接口?通常我們使用Swagger都是通過指定要掃描的包或者掃描具有某些注解的Controller,來生成API,那么如果這其中還想過濾掉一些特定API怎么做呢?
實現方法
1、添加特性,隱藏swagger接口特性標識
/// <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); } } } } }
2、添加過濾器,自定義Swagger隱藏過濾器
/// <summary> /// 隱藏swagger接口特性標識 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class HiddenApiAttribute : System.Attribute { }
3、修改SwaggerConfig,注入過濾器
#region Swagger services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "接口文檔", Description = "接口文檔-基礎", TermsOfService = "https://example.com/terms", Contact = new Contact { Name = "XXX1111", Email = "XXX1111@qq.com", Url = "https://example.com/terms" } , License = new License { Name = "Use under LICX", Url = "https://example.com/license", } }); c.SwaggerDoc("v2", new Info { Version = "v2", Title = "接口文檔", Description = "接口文檔-基礎", TermsOfService = "https://example.com/terms", Contact = new Contact { Name = "XXX2222", Email = "XXX2222@qq.com", Url = "https://example.com/terms" } , License = new License { Name = "Use under LICX", Url = "https://example.com/license", } }); c.OperationFilter<HttpHeaderOperationFilter>(); c.DocumentFilter<HiddenApiFilter>(); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"CompanyName.ProjectName.ICommonServer.xml")); }); #endregion Swagger
測試
/////// <summary> /////// 檢測帳號是不已存在 /////// </summary> /////// <param name="account">(必填)帳號或手機號 Data=true 已存在,Data=false 不存在</param> /////// <returns>測試</returns> ////[HttpGet, Route("existAccount")] ////[ApiExplorerSettings(GroupName = "v2")] //////[HiddenApi] ////public R<bool> ExistAccount([FromQuery] string account) ////{ //// return R<bool>.Suc(true); ////}
開源地址
https://github.com/conanl5566/Sampleproject/tree/master/src/03%20Host/CompanyName.ProjectName.HttpApi.Host