Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement api versioning and swagger document dynamically

Tags:

.net-core

I am working in dotnet core api. I have to implement versioning on api. and swagger document should be categorized by api version.

like image 736
Shersingh Chouhan Avatar asked Oct 17 '25 03:10

Shersingh Chouhan


1 Answers

In .NetCore api versioning can be implement by adding below reference from nuget

  1. Microsoft.AspNetCore.Mvc.Versioning
  2. Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer

After adding reference do following in startup file of your project. Add below line before AddMvc line. I will use Header-api versioning. It means client will mention the version in header. Header name is customizable.

 services.AddApiVersioning(this.Configuration);

Definition of AddApiVersioning would be like as (In different extension class):

public static void AddApiVersioning(this IServiceCollection services, IConfiguration configuration)
{
    services.AddApiVersioning(apiVersioningOptions =>
    {
        apiVersioningOptions.ApiVersionReader = new HeaderApiVersionReader(new string[] { "api-version" }); // It means version will be define in header.and header name would be "api-version".
        apiVersioningOptions.AssumeDefaultVersionWhenUnspecified = true;
        var apiVersion = new Version(Convert.ToString(configuration["DefaultApiVersion"]));
        apiVersioningOptions.DefaultApiVersion = new ApiVersion(apiVersion.Major, apiVersion.Minor);
        apiVersioningOptions.ReportApiVersions = true;
        apiVersioningOptions.UseApiBehavior = true; // It means include only api controller not mvc controller.
        apiVersioningOptions.Conventions.Controller<AppController>().HasApiVersion(apiVersioningOptions.DefaultApiVersion);
        apiVersioningOptions.Conventions.Controller<UserController>().HasApiVersion(apiVersioningOptions.DefaultApiVersion);               
        apiVersioningOptions.ApiVersionSelector = new CurrentImplementationApiVersionSelector(apiVersioningOptions);
    });
    services.AddVersionedApiExplorer(); // It will be used to explorer api versioning and add custom text box in swagger to take version number.
}

Here configuration["DefaultApiVersion"] is a key in appsetting having value 1.0 As in above code we have used Convention to define api version for each controller. It is useful when there is one api version and you don't want to label each controller with [ApiVersion] attribute.

If you don't want to use the Convention menthod to define version of controller. use attribute label to define version. like as below:

[Route("[controller]")]
[ApiController]
[ApiVersion("1.0")]
public class TenantController : ConfigController

Once this done go to StartUp file and add below code.

 app.UseApiVersioning(); //Here app is IApplicationBuilder

That is complete solution for api versioning.

For swagger We have to add nuget package as defined below:

  1. Swashbuckle.AspNetCore
  2. Swashbuckle.AspNetCore.SwaggerGen
  3. Swashbuckle.AspNetCore.SwaggerUI After adding reference do below: Add below line after Services.UseApiVersioning()

services.AddSwaggerGenerationUI();

The definition of AddSwaggerGenerationUI is below in extens :

public static void AddSwaggerGenerationUI(this IServiceCollection services)
{
    var provider = services.BuildServiceProvider()
                     .GetRequiredService<IApiVersionDescriptionProvider>();
    services.AddSwaggerGen(action =>
    {                
        action.OrderActionsBy(orderBy => orderBy.HttpMethod);
        action.UseReferencedDefinitionsForEnums();
        foreach (var item in provider.ApiVersionDescriptions)
        {
            action.SwaggerDoc(item.GroupName, new Swashbuckle.AspNetCore.Swagger.Info
            {
                Title = "Version-" + item.GroupName,
                Version = item.ApiVersion.MajorVersion.ToString() + "." + item.ApiVersion.MinorVersion
            });
        }
    });
}

This code will add swagger in pipeline. Now we have to use swagger. do below code in startup file.:

app.UseSwaggerGenerationUI(this.Configuration)

Definition of UseSwaggerGenerationUI would be like as :

public static void UseSwaggerGenerationUI(this IApplicationBuilder applicationBuilder, IApiVersionDescriptionProvider apiVersionDescriptionProvider, IConfiguration configuration)
{
    applicationBuilder.UseSwagger(c =>
    {
        c.RouteTemplate = "/api/help/versions/{documentname}/document.json";

        c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.BasePath = "/api");
    });

    applicationBuilder.UseSwaggerUI(c =>
    {
        c.RoutePrefix = "api/help";
        c.DocumentTitle = "Api Help";
        foreach (var item in apiVersionDescriptionProvider.ApiVersionDescriptions)
        {
            c.SwaggerEndpoint($"/api/help/versions/{item.GroupName}/document.json", item.GroupName);
        }
    });
}
like image 50
Dalip Choudhary Avatar answered Oct 19 '25 09:10

Dalip Choudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!