An API rarely stays the same throughout the lifetime of an application. As business requirements change, developers add new fields, modify request models, introduce new endpoints, and update existing operations. These changes are normal, but they can create problems when multiple applications depend on the same API.
Consider an ASP.NET Core API used by a mobile application, an admin portal, and an external integration. The mobile application may not receive an update immediately because users do not install new versions at the same time. The external integration may be maintained by another team that releases updates only a few times a year. If the API changes its response structure without considering these clients, existing applications can stop working even though the API itself is running correctly.
API versioning provides a way to evolve an application while continuing to support older clients. Instead of replacing an existing contract immediately, the API can expose a new version and allow consumers to migrate when they are ready.
This article explains how to introduce API versioning in ASP.NET Core, maintain multiple versions, handle deprecated endpoints, and organize version changes without unnecessarily breaking existing .NET clients.
Why API Versioning Matters
Suppose an application initially exposes the following endpoint:
GET /api/customers/10
It returns customer information:
{
"id": 10,
"name": "John",
"email": "[email protected]"
}
A new business requirement asks the development team to return the customer's full name, contact number, and account status. The team decides to change the response:
{
"customerId": 10,
"fullName": "John Smith",
"phoneNumber": "9876543210",
"status": "Active"
}
The new response may be more useful, but it is not compatible with every existing client. An older mobile application may still expect the id and name properties. A third-party integration may also depend on the previous response structure.
There are several ways to manage this situation, but simply replacing the old response is risky. API versioning allows the application to keep the original contract available while introducing a new one.
For example:
/api/v1/customers/10
/api/v2/customers/10
The first endpoint continues returning the original response, while the second returns the updated structure.
This separation gives existing clients time to migrate without forcing every consumer to update simultaneously. It is especially useful for public APIs, mobile applications, partner integrations, and systems where different clients follow different release schedules.
Add API Versioning to an ASP.NET Core Application
ASP.NET Core does not require developers to implement all API versioning behavior manually. The Asp.Versioning libraries provide versioning support for controllers and Minimal APIs.
For a controller-based application, install the required packages:
dotnet add package Asp.Versioning.Mvc
dotnet add package Asp.Versioning.Mvc.ApiExplorer
The first package provides API versioning for ASP.NET Core MVC controllers. The second integrates version information with API exploration, which is useful when generating separate OpenAPI documents.
Configure versioning in Program.cs:
using Asp.Versioning;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
})
.AddMvc()
.AddApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
var app = builder.Build();
app.MapControllers();
app.Run();
There are three important settings in this configuration.
DefaultApiVersion defines the version that the application uses when a client does not provide one. AssumeDefaultVersionWhenUnspecified allows requests without an explicit version to use that default. This can be important when introducing versioning into an API that already has existing clients.
ReportApiVersions enables response headers that advertise supported and deprecated versions. These headers help clients and monitoring systems understand the API's version status.
The API Explorer integration groups endpoint descriptions by version and replaces version placeholders in route templates. This is useful when generating documentation for each API version.
The default-version behavior deserves particular attention. If an existing API has never required clients to specify a version, suddenly requiring one can break those clients. Assuming the existing version during migration provides a smoother transition. For a newly designed API, requiring explicit versions may be a better choice.
Create Separate Versions of an API Controller
Once versioning is configured, you can define which API versions a controller supports.
Consider a customer API that originally returns a simple customer response. The first version can remain unchanged while the second version introduces a new response model.
Create the version 1 response:
public sealed class CustomerResponseV1
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
Create the version 2 response:
public sealed class CustomerResponseV2
{
public int CustomerId { get; set; }
public string FullName { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Status { get; set; } = string.Empty;
}
You can now define separate controllers for each version.
Version 1:
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/customers")]
public sealed class CustomersV1Controller : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<CustomerResponseV1> Get(int id)
{
var customer = new CustomerResponseV1
{
Id = id,
Name = "John Smith",
Email = "[email protected]"
};
return Ok(customer);
}
}
Version 2:
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion(2.0)]
[Route("api/v{version:apiVersion}/customers")]
public sealed class CustomersV2Controller : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<CustomerResponseV2> Get(int id)
{
var customer = new CustomerResponseV2
{
CustomerId = id,
FullName = "John Smith",
PhoneNumber = "9876543210",
Status = "Active"
};
return Ok(customer);
}
}
Both controllers use the same resource path, but their route templates include different API versions.
The resulting requests are:
GET /api/v1/customers/10
GET /api/v2/customers/10
The version 1 endpoint continues returning the original response, while version 2 provides the updated structure.
In a production application, both controllers should normally call the same application service or domain layer. Version-specific controllers and response models should handle the differences in the HTTP contract, not duplicate the business logic.
For example, both versions can retrieve the same customer entity and map it to their respective response models. This keeps business rules consistent while allowing the public API to evolve.
Choose an API Versioning Strategy
ASP.NET Core API versioning supports different ways for clients to identify the version they want. The choice affects how clients construct requests and how the application manages routes.
URL segment versioning
This approach includes the version in the URL:
GET /api/v1/customers/10
GET /api/v2/customers/10
It is straightforward to understand and easy to test. Developers can also see the requested API version in server logs, browser tools, and request traces.
URL segment versioning is a practical choice for public REST APIs and applications where different versions need to remain visible as separate routes.
Query string versioning
The client sends the version as a query parameter:
GET /api/customers/10?api-version=1.0
A newer client can request:
GET /api/customers/10?api-version=2.0
This approach keeps the route structure unchanged. However, developers must ensure that API gateways, caches, and monitoring systems account for the version query parameter when identifying requests.
Header versioning
The version can also be supplied through an HTTP header:
GET /api/customers/10
x-api-version: 2.0
This keeps version information out of the URL and can be useful when an organization already has a standard for custom request headers.
Configure a custom version header with:
builder.Services
.AddApiVersioning(options =>
{
options.ApiVersionReader =
new HeaderApiVersionReader("x-api-version");
});
Header versioning is less visible when someone looks at a URL, so debugging and manual testing require attention to request headers.
For most applications, the best strategy is the one that fits existing client conventions and infrastructure. Avoid changing the versioning strategy after clients have already started depending on it unless there is a clear migration plan.
Keep Business Logic Shared Across API Versions
Creating separate controllers does not mean creating separate business logic for every version.
A common mistake is copying the entire controller and service implementation when introducing a new API version. Over time, the two implementations start behaving differently. A bug fixed in version 1 may remain in version 2, or a business rule may be updated in only one place.
A better approach is to keep shared application behavior in a service and map the result into version-specific response models.
For example:
public sealed class CustomerService
{
public Customer GetCustomer(int id)
{
return new Customer
{
Id = id,
FirstName = "John",
LastName = "Smith",
Email = "[email protected]",
PhoneNumber = "9876543210",
IsActive = true
};
}
}
The version 1 controller can map the result to its original contract:
[HttpGet("{id:int}")]
public ActionResult<CustomerResponseV1> Get(
int id,
[FromServices] CustomerService service)
{
var customer = service.GetCustomer(id);
var response = new CustomerResponseV1
{
Id = customer.Id,
Name = $"{customer.FirstName} {customer.LastName}",
Email = customer.Email
};
return Ok(response);
}
The version 2 controller can expose the additional information:
[HttpGet("{id:int}")]
public ActionResult<CustomerResponseV2> Get(
int id,
[FromServices] CustomerService service)
{
var customer = service.GetCustomer(id);
var response = new CustomerResponseV2
{
CustomerId = customer.Id,
FullName = $"{customer.FirstName} {customer.LastName}",
PhoneNumber = customer.PhoneNumber,
Status = customer.IsActive ? "Active" : "Inactive"
};
return Ok(response);
}
The examples use a simplified service for clarity. In a real application, register the service through dependency injection and use asynchronous methods when accessing a database or another remote service.
The important design principle is that version-specific code should focus on request and response compatibility. Business operations should remain shared whenever their behavior is the same.
Deprecate Older Versions Without Removing Them Immediately
Supporting multiple API versions does not mean keeping every version forever. Older versions eventually need to be retired, but removing them without warning can break applications that have not migrated.
A safer approach is to mark an older version as deprecated while continuing to support it.
For example:
[ApiController]
[ApiVersion(1.0, Deprecated = true)]
[Route("api/v{version:apiVersion}/customers")]
public sealed class CustomersV1Controller : ControllerBase
{
[HttpGet("{id:int}")]
public ActionResult<CustomerResponseV1> Get(int id)
{
return Ok(new CustomerResponseV1
{
Id = id,
Name = "John Smith",
Email = "[email protected]"
});
}
}
The version 1 endpoint remains available, but the API communicates that consumers should move to a newer version.
When version reporting is enabled, the API can return headers such as:
api-supported-versions: 1.0, 2.0
api-deprecated-versions: 1.0
This information can be used by monitoring tools and API clients to identify versions that need attention.
For a more structured retirement process, the Asp.Versioning libraries also support deprecation and sunset policies. These can communicate when a version is deprecated and when it is expected to become unavailable through HTTP headers such as Deprecation and Sunset.
Deprecation and removal should be treated as separate steps. First announce the change, provide migration guidance, monitor usage, and give consumers sufficient time to update. Only then should the old implementation be removed according to the published support policy.
Generate Separate OpenAPI Documents for Each Version
When an API supports multiple versions, its documentation should make the differences clear. A single document that mixes every version can become difficult for developers and generated client tools to understand.
The API Explorer integration helps group endpoints by version. For example, the configuration shown earlier uses:
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
This produces version-specific API descriptions that can be used by OpenAPI generation tools.
ASP.NET Core's built-in OpenAPI support can generate multiple documents by registering different document names:
builder.Services.AddOpenApi("v1");
builder.Services.AddOpenApi("v2");
However, registering multiple document names alone does not automatically separate versioned endpoints. Each document must be configured to include the appropriate endpoints. The ShouldInclude option can be used to filter the API descriptions based on their version metadata.
Keeping separate OpenAPI documents helps mobile developers, frontend teams, and external consumers select the contract that matches their application. It also makes automated compatibility checks easier because each published version can be reviewed independently.
Test Older Versions Before Releasing Changes
API versioning protects existing contracts only when those contracts continue to work. Developers should test older versions whenever shared services, database mappings, authentication, or business rules change.
For example, an integration test can verify that version 1 still returns the original response properties:
[Fact]
public async Task GetCustomerV1_ReturnsOriginalResponse()
{
using var response = await _client.GetAsync(
"/api/v1/customers/10");
response.EnsureSuccessStatusCode();
var customer = await response.Content
.ReadFromJsonAsync<CustomerResponseV1>();
Assert.NotNull(customer);
Assert.Equal(10, customer.Id);
Assert.Equal("John Smith", customer.Name);
Assert.Equal("[email protected]", customer.Email);
}
A similar test should verify the version 2 response.
These tests should run in CI whenever a shared service or versioned endpoint changes. They help detect accidental modifications to older contracts before the application reaches production.
It is also useful to monitor which API versions are actually being used. Server logs, API gateway analytics, and client telemetry can help identify consumers that still depend on an older version. This information makes retirement decisions more reliable than choosing a removal date based only on assumptions.
Conclusion
API versioning allows ASP.NET Core applications to evolve without forcing every client to change at the same time. By keeping older contracts available, introducing new versions for incompatible changes, and sharing business logic across controllers, developers can reduce the risk of breaking existing applications.
The Asp.Versioning libraries provide a practical way to implement versioning for controllers and Minimal APIs. Combined with OpenAPI documentation, deprecation policies, integration tests, and usage monitoring, they provide a manageable process for maintaining APIs over time.
The goal is not to create a new API version for every small change. It is to recognize when a change affects the existing contract and provide a controlled migration path for the clients that depend on it.
Join the conversation! Your thoughts help the community grow.