生成器将在单个 Swagger 文档中包含所有 API 操作。但是,如有必要,您可以创建多个文档。例如,您可能希望每个 API 版本都有一个单独的文档。
案例
添加服务、中间件(v1、v2)
builder.Services.AddSwaggerGen(options =>
{
//定义多个Swagger 文档
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "v1 标题",
Version = "v1"
});
options.SwaggerDoc("v2", new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "v2 标题",
Version = "v2"
});
});
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1~~~");
options.SwaggerEndpoint("/swagger/v2/swagger.json", "v2~~~");
});
添加两个Controller,分别属于v1、v2:
namespace SwaggerVersion.Controllers.v1
{
[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(GroupName = "v1")]
public class OrderController : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
namespace SwaggerVersion.Controllers.v2
{
[ApiController]
[Route("[controller]")]
[ApiExplorerSettings(GroupName = "v2")]
public class OrderController : ControllerBase
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
按约定为文档分配操作
您可以连接以下约定以根据控制器命名空间进行分组,就不需要[ApiExplorerSettings]
了
// ApiExplorerGroupPerVersionConvention.cs
public class ApiExplorerGroupPerVersionConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.V1"
var apiVersion = controllerNamespace.Split('.').Last().ToLower();
controller.ApiExplorer.GroupName = apiVersion;
}
}
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(c =>
c.Conventions.Add(new ApiExplorerGroupPerVersionConvention())
);
...
}
标签:Core,ASP,Group,options,v1,v2,文档,new,public
From: https://www.cnblogs.com/fanfan-90/p/16795604.html