您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)Asp.Net Core WebAPI如何使用Swagger時(shí)API隱藏和分組的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
1、前言
為什么我們要隱藏部分接口?
因?yàn)槲覀冊谟胹wagger代替接口的時(shí)候,難免有些接口會直觀的暴露出來,比如我們結(jié)合Consul一起使用的時(shí)候,會將健康檢查接口以及報(bào)警通知接口暴露出來,這些接口有時(shí)候會出于方便考慮,沒有進(jìn)行加密,這個(gè)時(shí)候我們就需要把接口隱藏起來,只有內(nèi)部的開發(fā)者知道。
為什么要分組?
通常當(dāng)我們寫前后端分離的項(xiàng)目的時(shí)候,難免會遇到編寫很多接口供前端頁面進(jìn)行調(diào)用,當(dāng)接口達(dá)到幾百個(gè)的時(shí)候就需要區(qū)分哪些是框架接口,哪些是業(yè)務(wù)接口,這時(shí)候給swaggerUI的接口分組是個(gè)不錯(cuò)的選擇。
swagger的基本使用這里將不再贅述,可以閱讀微軟官方文檔,即可基本使用
2、swaggerUI中加入授權(quán)請求
新建HttpHeaderOperationFilter操作過濾器,繼承Swashbuckle.AspNetCore.SwaggerGen.IOperationFilter
接口,實(shí)現(xiàn)Apply方法
/// <summary> /// swagger請求頭 /// </summary> public class HttpHeaderOperationFilter : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { #region 新方法 if (operation.Parameters == null) { operation.Parameters = new List<IParameter>(); } if (context.ApiDescription.TryGetMethodInfo(out MethodInfo methodInfo)) { if (!methodInfo.CustomAttributes.Any(t => t.AttributeType == typeof(AllowAnonymousAttribute)) &&!(methodInfo.ReflectedType.CustomAttributes.Any(t => t.AttributeType == typeof(AuthorizeAttribute)))) { operation.Parameters.Add(new NonBodyParameter { Name = "Authorization", In = "header", Type = "string", Required = true, Description = "請輸入Token,格式為bearer XXX" }); } } #endregion #region 已過時(shí) //if (operation.Parameters == null) //{ // operation.Parameters = new List<IParameter>(); //} //var actionAttrs = context.ApiDescription.ActionAttributes().ToList(); //var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); //if (isAuthorized == false) //{ // var controllerAttrs = context.ApiDescription.ControllerAttributes(); // isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute)); //} //var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); //if (isAuthorized && isAllowAnonymous == false) //{ // operation.Parameters.Add(new NonBodyParameter // { // Name = "Authorization", // In = "header", // Type = "string", // Required = true, // Description = "請輸入Token,格式為bearer XXX" // }); //} #endregion } }
然后修改Startup.cs中的ConfigureServices方法,添加我們自定義的HttpHeaderOperationFilter過濾器
public IServiceProvider ConfigureServices(IServiceCollection services) { ... services.AddSwaggerGen(c => { ... c.OperationFilter<HttpHeaderOperationFilter>(); }); ... }
這時(shí)候我們再訪問swaggerUI就可以輸入Token了
3、API分組
修改Startup.cs中的ConfigureServices方法,添加多個(gè)swagger文檔
public IServiceProvider ConfigureServices(IServiceCollection services) { ... services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "接口文檔", Description = "接口文檔-基礎(chǔ)", TermsOfService = "", Contact = new Contact { Name = "XXX1111", Email = "XXX1111@qq.com", Url = "" } }); c.SwaggerDoc("v2", new Info { Version = "v2", Title = "接口文檔", Description = "接口文檔-基礎(chǔ)", TermsOfService = "", Contact = new Contact { Name = "XXX2222", Email = "XXX2222@qq.com", Url = "" } }); //反射注入全部程序集說明 GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll")).ToList().ForEach(assembly => { c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml")); }); c.OperationFilter<HttpHeaderOperationFilter>(); //c.DocumentFilter<HiddenApiFilter>(); }); ... }
修改Startup.cs中的Configure方法,加入
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { ... app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v2/swagger.json", "接口文檔-基礎(chǔ)");//業(yè)務(wù)接口文檔首先顯示 c.SwaggerEndpoint("/swagger/v1/swagger.json", "接口文檔-業(yè)務(wù)");//基礎(chǔ)接口文檔放后面后顯示 c.RoutePrefix = string.Empty;//設(shè)置后直接輸入IP就可以進(jìn)入接口文檔 }); ... }
然后還要在我們的控制器上面標(biāo)注swagger文檔的版本
這時(shí)候我們就可以將接口文檔進(jìn)行分組顯示了
4、API隱藏
創(chuàng)建自定義隱藏特性HiddenApiAttribute.cs
/// <summary> /// 隱藏swagger接口特性標(biāo)識 /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public class HiddenApiAttribute:System.Attribute { }
創(chuàng)建API隱藏過濾器HiddenApiFilter繼承Swashbuckle.AspNetCore.SwaggerGen.IDocumentFilter
接口,實(shí)現(xiàn)Apply方法
/// <summary> /// 自定義Swagger隱藏過濾器 /// </summary> public class HiddenApiFilter : IDocumentFilter { 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); } } } } }
在Startup.cs中使用HiddenApiFilter
public IServiceProvider ConfigureServices(IServiceCollection services) { ... services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "接口文檔", Description = "接口文檔-基礎(chǔ)", TermsOfService = "", Contact = new Contact { Name = "XXX1111", Email = "XXX1111@qq.com", Url = "" } }); c.SwaggerDoc("v2", new Info { Version = "v2", Title = "接口文檔", Description = "接口文檔-基礎(chǔ)", TermsOfService = "", Contact = new Contact { Name = "XXX2222", Email = "XXX2222@qq.com", Url = "" } }); //反射注入全部程序集說明 GetAllAssemblies().Where(t => t.CodeBase.EndsWith("Controller.dll") && !t.CodeBase.Contains("Common.Controller.dll")).ToList().ForEach(assembly => { c.IncludeXmlComments(assembly.CodeBase.Replace(".dll", ".xml")); }); c.OperationFilter<HttpHeaderOperationFilter>(); c.DocumentFilter<HiddenApiFilter>(); }); ... }
示例:
我這里提供了Consul的心跳檢車接口
但是在接口文檔中并沒有顯示出來
感謝各位的閱讀!關(guān)于“Asp.Net Core WebAPI如何使用Swagger時(shí)API隱藏和分組”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。