本文涉及技術棧:.net(非.net core)。提前告知是便於大家鑒別這篇文章是否符合自己想要的,好多博客不分.net和.net core,會導致一些小白發現有的代碼拿過去根本就運行不通。如果閱讀者是別的語言,或者覺得無參考意義也可以移步他處,以此節省您的時間。
以下開始正文:
寫過webapi的大多用過swagger來生成在線文檔,方便調用接口人員的查閱和調試。這里就不介紹如何使用了,底部鏈接會給出參考資料,幫助您從零開始搭建swagger文檔。
文檔生成了,但是由於某些原因,我並不想讓我寫的某個接口顯示在文檔里,即這個接口不想暴露給別人,這個可以是我私下自己測試,或者別的什么接口,反正就不想顯示出來,出於這個考慮,我找了很多資料,最后得出方案如下:
第一步,新建過濾器:

using Swashbuckle.Swagger; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http.Description; namespace Apps.WebApi.Core { /// <summary> /// 隱藏接口,不生成到swagger文檔展示 /// 注意:如果不加[HiddenApi]標記的接口名稱和加過標記的隱藏接口名稱相同,則該普通接口也會被隱藏不顯示,所以建議接口名稱最好不要重復 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public partial class HiddenApiAttribute : Attribute { } /// <summary> /// /// </summary> public class SwaggerIgnoreFilter : IDocumentFilter { /// <summary> /// 重寫Apply方法,移除隱藏接口的生成 /// </summary> /// <param name="swaggerDoc">swagger文檔文件</param> /// <param name="schemaRegistry"></param> /// <param name="apiExplorer">api接口集合</param> public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer) { foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions) { if (Enumerable.OfType<HiddenApiAttribute>(apiDescription.GetControllerAndActionAttributes<HiddenApiAttribute>()).Any()) { string key = "/" + apiDescription.RelativePath; if (key.Contains("?")) { int idx = key.IndexOf("?", StringComparison.Ordinal); key = key.Substring(0, idx); } swaggerDoc.paths.Remove(key); } } } } }
第二步,swagger的配置文件中注入過濾器:

using System.Web.Http; using Swashbuckle.Application; using System.Web; using Apps.WebApi; using Apps.WebApi.Core; [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")] namespace Apps.WebApi { /// <summary> /// /// </summary> public class SwaggerConfig { /// <summary> /// /// </summary> public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "Apps.WebApi"); c.IncludeXmlComments(string.Format("{0}/bin/Apps.WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory)); //在接口類、方法標記屬性 [HiddenApi],可以阻止【Swagger文檔】生成 c.DocumentFilter<SwaggerIgnoreFilter>(); }) .EnableSwaggerUi(c => { }); } } }
第三步,api帶上過濾器屬性:
以上,最后生成的文檔就不會顯示加了過濾屬性的接口了。
參考資料:
1.ASP.NET Web API 使用Swagger使用筆記 (PS:這篇文章是幫助您搭建swagger文檔,里面關於漢化的代碼好像有點小問題,所以我沒搞漢化。一般開發也看得懂,如果需要漢化+參考這篇文章也遇到代碼錯誤的,需要另尋方法實現)
2.c# .Net 讓Swagger隱藏/忽略指定接口類或方法 (本文代碼基本就是照抄的該文章,只不過是我這里附帶了一下圖片,閱讀性會更好)