.NET Core 使用swagger進行分組顯示
阿新 • • 發佈:2021-01-10
其實,和swagger版本管理類似;只是平時介面太多;不好供前端人員進行篩選。
下面進入主題:
首先:
//註冊Swagger生成器,定義一個和多個Swagger 文件 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "公共模組", Description= "介面說明(多模式管理,右上角切換)", TermsOfService = "", Contact = new Contact { Name = "Fatefox", Email = "[email protected]" } }); c.SwaggerDoc("gp", new Info { Title = "登入模組", Version = "GP" }); c.SwaggerDoc("mom", new Info { Title = "業務模組", Version = "YW" }); c.SwaggerDoc("dm", new Info { Title = "其他模組", Version = "QT" }); //設定要展示的介面 c.DocInclusionPredicate((docName, apiDes) => { if (!apiDes.TryGetMethodInfo(out MethodInfo method))return false; /*使用ApiExplorerSettingsAttribute裡面的GroupName進行特性標識 * DeclaringType只能獲取controller上的特性 * 我們這裡是想以action的特性為主 * */ var version = method.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName); if (docName == "v1" && !version.Any()) return true; //這裡獲取action的特性 var actionVersion = method.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName); if (actionVersion.Any()) return actionVersion.Any(v => v == docName); return version.Any(v => v == docName); }); //新增授權 c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "請輸入帶有Bearer開頭的Token", Name = "Authorization", In = "header", Type = "apiKey" }); //認證方式,此方式為全域性新增 c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "Bearer", Enumerable.Empty<string>() } }); //c.OperationFilter<WebUserAPI.Common.AssignOperationVendorExtensions>(); //設定SjiggJSON和UI的註釋路徑. // 為 Swagger JSON and UI設定xml文件註釋路徑 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); var xmlPath = Path.Combine(basePath, "WebUserAPI.xml"); var xmlmodelPath = Path.Combine(basePath, "WebUserAPIMdoel.xml");//新增model註釋 c.IncludeXmlComments(xmlmodelPath); c.IncludeXmlComments(xmlPath, true);//controller註釋;必須放最後,否則後面的會覆蓋前面的 });
然後設定UI:
// 新增Swagger介面文件服務 app.UseSwagger(); //啟用SwaggerUI樣式 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "公共模組"); c.SwaggerEndpoint("/swagger/gp/swagger.json", "登入模組"); c.SwaggerEndpoint("/swagger/mom/swagger.json", "業務模組"); c.SwaggerEndpoint("/swagger/dm/swagger.json", "其他模組"); c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); });
最後就是使用啦:
在controller或者action上打上
ApiExplorerSettings(GroupName = "gp")
GroupName根據自己的命名進行分組就可以了.
總的來說和設定apiVersion類似,這裡就不多介紹了