Dot net Core Web API Versioning Implementation
Steps For API Versioning:
Add new NuGet package:
Microsoft.AspNetCore.Mvc.Versioning
Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer
Configure API Versioning Updating by startup. cs file with the following Code:
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(options =>
{
// add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
// note: the specified format code will format the version as "'v'major[.minor][-status]"
options.GroupNameFormat = "'v'VVV";
// note: this option is only necessary when versioning by url segment. the SubstitutionFormat
// can also be used to control the format of the API version in route templates
options.SubstituteApiVersionInUrl = true;
});
Configure API Versioning With Swagger Updating by StartUp.cs File
services.AddSwaggerGen(c =>
{
c.CustomSchemaIds(x => x.FullName);
// configure dropdown for Versioning in swagger page
c.SwaggerDoc("v1", new OpenApiInfo { Title = "GurooGlobalAPI verison 1", Version = "v1" });
c.SwaggerDoc("v2", new OpenApiInfo { Title = "GurooGlobalAPI verison 2", Version = "v2" });
});
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(
options =>
{
// build a swagger endpoint for each discovered API version
foreach (var description in provider.ApiVersionDescriptions)
{
options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
}
});
Configure and Map-Versioning With API Controller and API Action Methods.
Add Route Attribute With Routing string on API Controller
[Route("v{version:apiVersion}/[controller]")]
Add Multiple API versions support by that Controller
[ApiVersion("1")]
[ApiVersion("2")]
Map API version with Action Method
[MapToApiVersion("1")]
Ex.
[ApiController]
[ApiVersion("1")]
[ApiVersion("2")]
[Route("v{version:apiVersion}/[controller]")]
public class CredentialController : ControllerBase
{
[HttpPost]
[Route("GetToken")]
[MapToApiVersion("1")]
public async Task<ActionResult<string>> GetToken()
{
// api body
}
}
Comments
Post a Comment