Introduction
When we update an API, older applications may break if changes are made directly.
API Versioning helps us add new features without affecting existing users. It keeps the API stable and backward compatible.
Step 1: Install Package
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Step 2: Configure Versioning (Program.cs)
builder.Services.AddApiVersioning(options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ReportApiVersions = true;
});
This sets version 1.0 as the default version.
Step 3: Apply Version in Controller
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok("Products API V1");
}
}
Output
Request:
GET /api/v1/products
Response:
Products API V1
Conclusion
API Versioning in ASP.NET Core helps maintain backward compatibility and prevents breaking changes. It is a good practice to start versioning from the beginning of your project.