Search code examples
asp.net-mvcasp.net-web-apiswaggeraspnetboilerplateapi-versioning

How to do versioning in ASP.NET Boilerplate Web API?


I am trying to do versioning in ASP.NET Boilerplate framework.

I have created two versions in Swagger Gen ("v1.0" and "v2.0") and set API version for Web API, but every time I get all API in both versions from Swagger.

Startup.cs:

AddSwaggerGen in ConfigureServices():

services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1.0", new Info { Title = "My API", Version = "v1.0" });
    options.SwaggerDoc("v2.0", new Info { Title = "My API", Version = "v2.0" });
    options.DocInclusionPredicate((docName, description) => true);

    // Define the BearerAuth scheme that's in use
    options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = "header",
        Type = "apiKey"
    });
    // Assign scope requirements to operations based on AuthorizeAttribute
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

UseSwaggerUI in Configure():

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); 

    app.UseCors(_defaultCorsPolicyName); 

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseAbpRequestLocalization();

    app.UseSignalR(routes =>
    {
        routes.MapHub<AbpCommonHub>("/signalr");
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "defaultWithArea",
            template: "{area}/{controller=Home}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    app.UseSwagger();

    app.UseSwaggerUI(options =>
    {
        options.InjectOnCompleteJavaScript("/swagger/ui/abp.js");
        options.InjectOnCompleteJavaScript("/swagger/ui/on-complete.js");
        options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My API V1.0");
        options.SwaggerEndpoint("/swagger/v2.0/swagger.json", "My API V2.0");
    }); 
}

API Controller - v1.0:

[ApiVersion("v1.0")]
[Route("/api/invoicemodule/1.0/[controller]")]
public class InvoiceController : MyControllerBase
{       
    [HttpGet, MapToApiVersion("v1.0")]
    public IActionResult GetInvoiceById(string invoiceid)
    {
        //BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);

        if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id' cannot be null or empty.");

        try
        {
            BusinessModels.Invoice sp = new BusinessModels.Invoice
            {
                Id = ""
            };
            if (sp != null)
            {
                return Ok(sp);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
}

API Controller - v2.0:

[ApiVersion("v2.0")]
[Route("/api/invoicemodule/2.0/[controller]")]
public class InvoiceController : MyControllerBase
{
    [HttpGet, MapToApiVersion("v2.0")]
    public IActionResult GetInvoiceById(string invoiceid)
    {
        //BusinessService.SparePartHistoryService sas = new BusinessService.SparePartHistoryService(_logger, _localizer, _configuration);

        if (string.IsNullOrEmpty(invoiceid)) return BadRequest("'Id' cannot be null or empty.");

        try
        {
            BusinessModels.Invoice sp = new BusinessModels.Invoice
            {
                Id = ""
            };
            if (sp != null)
            {
                return Ok(sp);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception e)
        {
            return BadRequest(e.Message);
        }
    }
}

Output

Version v1 output in swagger

enter image description here


Solution

  • Yeah, I got the solution

    Reference : https://github.com/domaindrivendev/Swashbuckle.AspNetCore

    I have changed little code of Service.AddSwaggerGen() in ConfigurationService() method of Startup.cs file

    Comments added in code where i have changed

          services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info { Version = "1" }); // Version must require in integer. can't set Version = "v1"
                options.SwaggerDoc("v2", new Info { Version = "2" });
                options.DocInclusionPredicate((docName, description) =>
                { // insert this {} code instead of "true" 
                    var versions = description.ControllerAttributes()
                    .OfType<ApiVersionAttribute>()
                    .SelectMany(attr => attr.Versions);
    
                    return versions.Any(v => $"v{v.ToString()}" == docName);
                });
            });