Details
.NET 8 Web API Versioning
To add API versioning to your .NET 8 Web API, follow these steps:
Install the Microsoft.AspNetCore.Mvc.Versioning
NuGet package
In your Program.cs
file, configure API versioning by adding the necessary services
// Configure API version
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
options.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("X-Api-Version"));
}).AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'V";
options.SubstituteApiVersionInUrl = true;
});
Use the [ApiVersion]
attribute on your controllers to specify which versions they support
For example, the version one controller could be…
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("This is version 1.0");
}
}
And the version two controller could be…
[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsV2Controller : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("This is version 2.0");
}
}
And that's it!
You could improve the folder structure to something like this
to enhance maintainability
/Controllers
/V1
- ProductsController.cs
- OrdersController.cs
- CustomersController.cs
- VendorsController.cs
/V2
- ProductsController.cs
- OrdersController.cs
- CustomersController.cs
- VendorsController.cs
/V3
- ProductsController.cs
- OrdersController.cs
- CustomersController.cs
- VendorsController.cs
To get Swagger support, add the following to your SwaggerGen
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
c.SwaggerDoc("v2", new OpenApiInfo { Title = "Your API", Version = "v2" });
c.SwaggerDoc("v3", new OpenApiInfo { Title = "Your API", Version = "v3" });
// Configure other Swagger options if needed
});
Easy!