asp.net-coreswaggernswagnswagstudioaspnet-api-versioning

NSwag and multiple api versions


Consider controllers below:

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 */ }
    }
}

And Swagger documents in 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";
    };
});

Now after testing the API browser with NSwag it ignores the versions and shows all the APIs in both v1 and v2 document.

How to tell NSwag to separate them?


Solution

  • I think you are missing ApiGroupNames property which is used to select Api version. Please add ApiGroupNames property like below code and let us know.

    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" };
    });