.NET Core 使用swagger进行分组显示
其实,和swagger版本管理类似;只是平时接口太多;不好供前端人员进行筛选。
下面进入主题:
首先:
//注册Swagger生成器,定义一个和多个Swagger 文档 services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "公共模块", Description = "接口说明(多模式管理,右上角切换)", TermsOfService = "", Contact = new Contact { Name = "Fatefox", Email = "476515159@qq.com" } }); 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类似,这里就不多介绍了
转载于:https://www.cnblogs.com/FateHuli/p/10821018.html
.NET Core 使用swagger进行分组显示
原文:https://www.cnblogs.com/superfeeling/p/15309699.html