.NET Core 使用swagger进行分组显示
使用swagger分组有两种方式,一种使用json配置,方式更加灵活,两外一种可使用枚举。
在appsetting.json中添加一个swagger配置
"SwaggerConfig": [ { "GroupName": "User", "Title": "用户管理", "Version": "V1" }, { "GroupName": "Sys", "Title": "系统管理", "Version": "V1" } ]
新建一个class类
public class SwaggerConfig { public string GroupName { get; set; } public string Title { get; set; } public string Version { get; set; } }
修改Startup,添加swagger
public void ConfigureServices(IServiceCollection services) { //services.AddControllers(); //返回的API中文不使用utf-8编码 services.AddControllers().AddJsonOptions(cfg => { cfg.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All); }); #region Swagger services.AddSwaggerGen(c => { var data = Configuration.GetSection("SwaggerConfig").Get<List<SwaggerConfig>>(); Configuration.GetSection("SwaggerConfig").Get<List<SwaggerConfig>>().ForEach(group => { c.SwaggerDoc(group.GroupName, new OpenApiInfo { Title = group.Title, Version = group.Version }); }); string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); string xmlPath = Path.Combine(basePath, "SwaggerGroup.xml"); c.IncludeXmlComments(xmlPath, true); }); #endregion }
修改Configure方法,添加SwaggerEndpoint对应的配置项
app.UseSwagger(); app.UseSwaggerUI(c => { //c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Document"); Configuration.GetSection("SwaggerConfig").Get<List<SwaggerConfig>>().ForEach(group => { c.SwaggerEndpoint($"/swagger/{group.GroupName}/swagger.json", group.Title); //分组显示 }); });
需要分组的控制器表头添加此属性即可
[ApiExplorerSettings(GroupName = "Sys")]
第二种方式,新建一个枚举类型
public enum OpenApiGroup { [Description("用户管理")] User = 1, [Description("系统管理")] Sys = 2 }
修改startup
#region Swagger 第二种方式 services.AddSwaggerGen(c => { typeof(OpenApiGroup).GetEnumNames().ToList().ForEach(version => { c.SwaggerDoc(version, new OpenApiInfo() { Title = $"{version}:Swagger文档", Version = version, Description = $"Panda.Sewerage : {version} " }); }); string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location); string xmlPath = Path.Combine(basePath, "SwaggerGroup.xml"); c.IncludeXmlComments(xmlPath, true); }); #endregion
修改Configure方法,添加SwaggerEndpoint对应的配置项
#region Swagger分组第二种 app.UseSwagger(); app.UseSwaggerUI(c => { //c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Document"); typeof(OpenApiGroup).GetEnumNames().ToList().ForEach(version => { c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}"); }); }); #endregion
控制器使用方式和第一种类似