通常一个项目中有很多的功能模块,每个功能模块又可能对应很多的接口,如果所有的接口都在一个列表显示,显然是比较混乱的,不便于调用方阅读和查找。
当然Swagger为我们已经考虑到了这一点,它能支持分组显示,具体怎么做呢,请看下面的配置:
在ConfigureServices方法中新增如下代码
using System.ComponentModel;
namespace DFTech.Service.Filters
{
public enum OpenApiGroup
{
[Description("wps管理")]
wps = 1,
[Description("诉前法律管理")]
sqfl = 2
}
}
builder.Services.AddSwaggerGen(options =>
{
List<string > list = new List<string>();
foreach (var e in Enum.GetValues(typeof(OpenApiGroup)))
{
// 转换成Description后添加至List
object objArr = e.GetType().GetField(e.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
var name = (objArr as DescriptionAttribute).Description;
//OpType opType = new OpType();
//opType.Key = (int)(EnumOperType)e;
//opType.Text = name;
list.Add(name);
}
// typeof(OpenApiGroup).GetEnumNames().ToList()
list.ForEach(version =>
{
options.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");
// options.IncludeXmlComments(xmlPath, true);
////options.SwaggerDoc("v1", new OpenApiInfo
////{
//// Version = "v1",
//// Title = "DFTech API",
//// Description = "DFTech API"
////});
var docs = new List<string>() {
Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"),
Path.Combine(AppContext.BaseDirectory, $"DFTech.Entities.xml")
};
docs.ForEach(x => options.IncludeXmlComments(x));
options.DocumentFilter<SwaggerEnumFilter>();
});
在Configure方法中新增如下代码
builder.Services.AddLogging(m => { m.AddNLog(); });
var app = builder.Build();
//app.Urls.Add("http://*:8081");
app.UseMiddleware<SwaggerBasicAuthMiddleware>();
// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
List<string> list = new List<string>();
foreach (var e in Enum.GetValues(typeof(OpenApiGroup)))
{
// 转换成Description后添加至List
object objArr = e.GetType().GetField(e.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), true)[0];
var name = (objArr as DescriptionAttribute).Description;
//OpType opType = new OpType();
//opType.Key = (int)(EnumOperType)e;
//opType.Text = name;
list.Add(name);
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api Document");
//typeof(OpenApiGroup).GetEnumNames().ToList()
list.ForEach(version =>
{
c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{version}");
});
});
//}
在Controller类上指定分组名
/// <summary>
/// 法信 智能问答
/// </summary>
[ApiExplorerSettings(GroupName = "诉前法律管理")]
[Route("api/consult")]
public class ConsultController : BaseApiController
{
private readonly IConfiguration _config;