關於.NET CORE 的 swagger 分組簡單使用
阿新 • • 發佈:2021-12-24
在避免swagger介面過多時,可以使用分組進行功能區分
簡單三部曲
1、新增分組和級別名稱
services.AddSwaggerGen(c => { #region swagger分組 c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "公共模組", Description= "介面說明(多模式管理,右上角切換)", }); c.SwaggerDoc("khgl", new OpenApiInfo { Title = "客戶管理", Version = "khgl" }); c.SwaggerDoc("htgl", new OpenApiInfo { Title = "合同管理", Version = "htgl" }); c.SwaggerDoc("yygl", new OpenApiInfo { Title = "運營管理", Version = "yygl" }); c.SwaggerDoc("jxgl", new OpenApiInfo { Title = "績效管理", Version = "jxgl" }); c.SwaggerDoc("kqgl", new OpenApiInfo { Title = "考勤管理", Version = "kqgl" }); c.SwaggerDoc("ldjsc", new OpenApiInfo { Title = "領導駕駛艙", Version = "ldjsc" }); c.SwaggerDoc("xtgl", new OpenApiInfo { Title = "系統管理", Version = "xtgl" }); c.SwaggerDoc("sbgl", new OpenApiInfo { Title = "裝置管理", Version = "sbgl" }); c.SwaggerDoc("excel", new OpenApiInfo { Title = "檔案下載", Version = "excel" }); //設定要展示的介面 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); }); #endregion
2、
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); //以下為關鍵程式碼 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "公共模組"); c.SwaggerEndpoint("/swagger/khgl/swagger.json", "客戶管理"); c.SwaggerEndpoint("/swagger/htgl/swagger.json", "合同管理"); c.SwaggerEndpoint("/swagger/yygl/swagger.json", "運營管理"); c.SwaggerEndpoint("/swagger/jxgl/swagger.json", "績效管理"); c.SwaggerEndpoint("/swagger/kqgl/swagger.json", "考勤管理"); c.SwaggerEndpoint("/swagger/ldjsc/swagger.json", "領導駕駛艙"); c.SwaggerEndpoint("/swagger/xtsz/swagger.json", "系統設定"); c.SwaggerEndpoint("/swagger/sbgl/swagger.json", "裝置管理"); c.SwaggerEndpoint("/swagger/excel/swagger.json", "檔案下載"); c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None); }); }
3、控制器使用
[Route("api/[controller]/[action]")] //使用 [ApiExplorerSettings(GroupName = "jxgl")]