其实,和swagger版本管理类似;只是平时接口太多;不好供前端人员进行筛选。
下面进入主题:
首先:
1 //注册Swagger生成器,定义一个和多个Swagger 文档 2 services.AddSwaggerGen(c => 3 { 4 c.SwaggerDoc("v1", new Info 5 { 6 Version = "v1", 7 Title = "公共模块", 8 Description = "接口说明(多模式管理,右上角切换)", 9 TermsOfService = "", 10 Contact = new Contact { Name = "Fatefox", Email = "476515159@qq.com" } 11 }); 12 c.SwaggerDoc("gp", new Info { Title = "登录模块", Version = "GP" }); 13 c.SwaggerDoc("mom", new Info { Title = "业务模块", Version = "YW" }); 14 c.SwaggerDoc("dm", new Info { Title = "其他模块", Version = "QT" }); 15 //设置要展示的接口 16 c.DocInclusionPredicate((docName, apiDes) => 17 { 18 if (!apiDes.TryGetMethodInfo(out MethodInfo method)) 19 return false; 20 /*使用ApiExplorerSettingsAttribute里面的GroupName进行特性标识 21 * DeclaringType只能获取controller上的特性 22 * 我们这里是想以action的特性为主 23 * */ 24 var version = method.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName); 25 if (docName == "v1" && !version.Any()) 26 return true; 27 //这里获取action的特性 28 var actionVersion = method.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(m => m.GroupName); 29 if (actionVersion.Any()) 30 return actionVersion.Any(v => v == docName); 31 return version.Any(v => v == docName); 32 }); 33 //添加授权 34 c.AddSecurityDefinition("Bearer", new ApiKeyScheme 35 { 36 Description = "请输入带有Bearer开头的Token", 37 Name = "Authorization", 38 In = "header", 39 Type = "apiKey" 40 }); 41 //认证方式,此方式为全局添加 42 c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> 43 { 44 { "Bearer", Enumerable.Empty<string>() } 45 }); 46 //c.OperationFilter<WebUserAPI.Common.AssignOperationVendorExtensions>(); 47 //设置SjiggJSON和UI的注释路径. 48 // 为 Swagger JSON and UI设置xml文档注释路径 49 var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); 50 var xmlPath = Path.Combine(basePath, "WebUserAPI.xml"); 51 var xmlmodelPath = Path.Combine(basePath, "WebUserAPIMdoel.xml");//添加model注释 52 c.IncludeXmlComments(xmlmodelPath); 53 c.IncludeXmlComments(xmlPath, true);//controller注释;必须放最后,否则后面的会覆盖前面的 54 });
然后设置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类似,这里就不多介绍了