API Versioning is the practice of managing changes to an API over time. As APIs evolve, new features are added, and older features might become deprecated. Versioning ensures backward compatibility for clients using older versions while providing access to new features for those on updated versions.
API versioning is essential when you need to support multiple versions of your API for different
clients or applications. .NET provides built-in support for versioning through the
Microsoft.AspNetCore.Mvc.Versioning
package.
Follow these steps to add API versioning to your .NET project:
// Install the package via NuGet
Install-Package Microsoft.AspNetCore.Mvc.Versioning
The Microsoft.AspNetCore.Mvc.Versioning
package provides tools for managing API versions.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add API versioning services
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
var app = builder.Build();
app.MapControllers();
app.Run();
DefaultApiVersion
: Specifies the default API version.AssumeDefaultVersionWhenUnspecified
: Assumes the default version if no version is specified.ReportApiVersions
: Includes supported versions in the response headers.
// Controllers/ProductsController.cs
[ApiController]
[Route("api/v{version:apiVersion}/products")]
[ApiVersion("1.0")]
public class ProductsV1Controller : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Product A (v1)", "Product B (v1)" });
}
}
[ApiController]
[Route("api/v{version:apiVersion}/products")]
[ApiVersion("2.0")]
public class ProductsV2Controller : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new[] { "Product A (v2)", "Product B (v2)", "Product C (v2)" });
}
}
Each versioned controller is decorated with the [ApiVersion]
attribute. The route includes
the version parameter.
// Example Requests:
// GET http://localhost:5000/api/v1/products => Returns products from version 1
// GET http://localhost:5000/api/v2/products => Returns products from version 2
Use tools like Postman or a browser to test the endpoints.
.NET supports multiple approaches for API versioning:
/api/v1/products
)./api/products?api-version=1.0
).api-version: 1.0
).