NSwag 和多个 api 版本

NSwag and multiple api versions

考虑以下控制器:

namespace Web.Controllers
{
    [ApiVersioning("1.0")
    [Route("api/v{version:apiVersion}/[controller]")]
    public class Product : ApiController
    {
        [HttpGet("id")]
        public IHttpActionResult<bool> GetProduct(Guid id) 
        { /* rest of the code */ }
    }
}

namespace Web.Controllers
{
    [ApiVersioning("2.0")
    [Route("api/v{version:apiVersion}/[controller]")]
    public class Product2 : ApiController
    {
        [HttpGet("id")]
        public IHttpActionResult<bool> GetProduct(Guid id) 
        { /* rest of the code */ }
    }
}

并且 Swagger 文档在 Startup class:

services.AddSwaggerDocument(config =>
{
    config.DocumentName = "v1.0";
    config.PostProcess = document =>
    {
        document.Info.Version = "v1.0";
    };
});

services.AddSwaggerDocument(config =>
{
    config.DocumentName = "v2.0";
    config.PostProcess = document =>
    {
        document.Info.Version = "v2.0";
    };
});

现在,在使用 NSwag 测试 API 浏览器后,它会忽略版本并在 v1 和 v2 文档中显示所有 API。

如何告诉 NSwag 将它们分开?

我认为您缺少用于 select Api 版本的 ApiGroupNames 属性。请像下面的代码一样添加 ApiGroupNames 属性 并告诉我们。

services.AddSwaggerDocument(config =>
{
    config.DocumentName = "v1.0";
    config.PostProcess = document =>
    {
        document.Info.Version = "v1.0";
    };
    config.ApiGroupNames = new[] { "1.0" };
});

services.AddSwaggerDocument(config =>
{
    config.DocumentName = "v2.0";
    config.PostProcess = document =>
    {
        document.Info.Version = "v2.0";
    };
    config.ApiGroupNames = new[] { "2.0" };
});