.Net5 Core 配置 Swagger 简单的给WebApi分组
Startup.cs下ConfigureServices代码
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "基础", Version = "v1" });
c.SwaggerDoc("v2", new OpenApiInfo { Title = "业务", Version = "v2" });
//c.DocInclusionPredicate((docName, description) => true);
c.DocInclusionPredicate((docName, apiDesc) =>
{
if(!apiDesc.TryGetMethodInfo(out MethodInfo menthodInfo)) return false;
var versions = menthodInfo.DeclaringType.GetCustomAttributes(true).OfType<ApiExplorerSettingsAttribute>().Select(attr => attr.GroupName);
if (docName.ToLower() == "v1" && versions.FirstOrDefault() == null)
{
return true;//若不使用[ApiExplorerSettings(GroupName= "GroupName")] api将在V1显示。
}
return versions.Any(v=>v.ToString()==docName);
});
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格",
Name = "Authorization",//jwt默认的参数名称
In =ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
Type =SecuritySchemeType.ApiKey
});
//认证方式,此方式为全局添加
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference()
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
}, Array.Empty<string>() }
});
});
Startup.cs下Configure代码
app.UseSwagger(c=>
{
c.RouteTemplate = "swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v2/swagger.json", "业务");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "基础");
}) ;
给Controllers或Action添加[ApiExplorerSettings(GroupName= "ApiGroupName")]
namespace XX.Controllers
{
[Authorize()]
[Route("api/[controller]")]
[ApiController]
[ApiExplorerSettings(GroupName = "v2")]
public class DataTreeController : Controller
{
private DataTreeService _datatreeService = null;
最终效果如下: