Introduction

API development does not stop after an endpoint is released. Over time, business requirements change, new features are introduced, and existing request and response structures may need updates. However, changing an API that is already being used by mobile applications, web applications, or third-party integrations requires careful planning.

One common challenge is handling older clients that continue using an existing API while the backend team introduces a newer version. For example, a mobile application installed several months ago may still send requests using an older request structure. If the backend directly modifies the existing API, those users may experience errors even though they have not updated their application.

ASP.NET Core provides API versioning support that allows developers to maintain multiple API versions without creating unnecessary compatibility problems. Instead of replacing an existing endpoint, developers can introduce a new version while keeping the older version available.

In this article, we will explore how API versioning works in ASP.NET Core, how to maintain older clients, how to introduce new API versions, and which practices help keep version management simple in production applications.

What Is API Versioning?

API versioning is a technique used to maintain multiple versions of an API so that different clients can communicate with the backend using the contract they support.

Consider an application that provides user profile information. Initially, the API returns the following response:

JSON
{
    "id": 101,
    "name": "John",
    "email": "[email protected]"
}

Later, the business requirement changes, and the application needs to return the user's phone number and account status.

The updated response might look like this:

JSON
{
    "id": 101,
    "name": "John",
    "email": "[email protected]",
    "phoneNumber": "9876543210",
    "accountStatus": "Active"
}

Adding optional response properties may not break most clients. However, changing existing property names, removing fields, modifying data types, or changing business behavior can introduce breaking changes.

API versioning provides a way to handle these changes without forcing every client to update immediately.

Why API Versioning Is Important

In production applications, different clients rarely update at the same time. A web application can often be updated centrally, but mobile applications depend on users downloading and installing newer releases.

For example, consider a mobile application with the following situation:

  • Version 1.0 of the mobile application uses API v1.
  • Version 2.0 introduces new profile functionality and uses API v2.
  • Some users continue using version 1.0.
  • New users install version 2.0.

If the backend removes or changes API v1 immediately, users running the older application may experience failures.

API versioning allows both clients to continue working while the development team gradually moves users toward the newer API.

Different API Versioning Approaches

ASP.NET Core API versioning supports different ways of identifying API versions. The most common approaches are URL path versioning, query string versioning, and header versioning.

ApproachExampleAdvantagesDisadvantages
URL path/api/v1/usersEasy to understand and testCreates separate versioned routes
Query string/api/users?api-version=1.0Simple to introduceVersion information is separate from the resource path
Headerapi-version: 1.0Keeps URLs cleanRequires additional client configuration

For most applications, URL path versioning is easy to understand because the API version is visible directly in the endpoint.

For example:

Code
/api/v1/users
/api/v2/users

The following implementation uses URL path versioning with ASP.NET Core controllers.

Implementing API Versioning in ASP.NET Core

ASP.NET Core applications can use the Asp.Versioning.Mvc package to implement API versioning.

Install the Required Package

Install the following NuGet package:

Bash
dotnet add package Asp.Versioning.Mvc

If the application also uses API Explorer for versioned Swagger documentation, install the API Explorer integration package:

Bash
dotnet add package Asp.Versioning.Mvc.ApiExplorer

These packages provide the versioning infrastructure and API discovery support needed for controller-based applications.

Configure API Versioning

Open Program.cs and configure API versioning through the dependency injection container.

C#
using Asp.Versioning;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);

        options.AssumeDefaultVersionWhenUnspecified = false;

        options.ReportApiVersions = true;
    })
    .AddMvc();

var app = builder.Build();

app.MapControllers();

app.Run();

Let's understand the important configuration options.

DefaultApiVersion defines the default version recognized by the versioning configuration.

AssumeDefaultVersionWhenUnspecified determines whether the configured default version should be used when a client does not specify a version. Setting it to false requires clients to provide an explicit version.

ReportApiVersions adds response headers that help clients identify supported and deprecated API versions.

This configuration provides a central place to manage API versioning behavior.

Creating the First API Version

Now, create an API controller for version 1.0.

For this example, the application provides a user profile endpoint.

C#
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/users")]
public class UsersV1Controller : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetUser(int id)
    {
        var user = new
        {
            Id = id,
            Name = "John",
            Email = "[email protected]"
        };

        return Ok(user);
    }
}

The ApiVersion attribute identifies this controller as belonging to version 1.0.

The route contains the version parameter, which allows ASP.NET Core to select the appropriate controller based on the requested API version.

For example:

Code
GET /api/v1/users/101

The endpoint returns the original user profile structure.

Once this API is released and clients start using it, its existing contract should be treated carefully.

Introducing a New API Version

Suppose the application now needs to return additional profile information, including the user's phone number and account status.

Instead of modifying the existing controller, create a separate controller for version 2.0.

C#
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/users")]
public class UsersV2Controller : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetUser(int id)
    {
        var user = new
        {
            Id = id,
            Name = "John",
            Email = "[email protected]",
            PhoneNumber = "9876543210",
            AccountStatus = "Active"
        };

        return Ok(user);
    }
}

Now, the application supports two API versions.

API EndpointVersionResponse
/api/v1/users/1011.0Original profile information
/api/v2/users/1012.0Extended profile information

Both controllers can operate independently while sharing the same underlying business services.

This approach makes it easier to introduce changes without disturbing existing clients.

Managing Shared Business Logic Across API Versions

One mistake developers sometimes make is duplicating the complete business logic inside every versioned controller.

For example, both API versions may contain the same database queries, authentication checks, and user retrieval logic. Maintaining duplicate code becomes difficult when business rules change.

A better approach is to keep business logic inside a shared service and let each controller handle its own response contract.

Consider the following service:

C#
public class UserService
{
    public User GetUserById(int id)
    {
        return new User
        {
            Id = id,
            Name = "John",
            Email = "[email protected]",
            PhoneNumber = "9876543210",
            AccountStatus = "Active"
        };
    }
}

public class User
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public string AccountStatus { get; set; }
}

Register the service in Program.cs:

C#
builder.Services.AddScoped<UserService>();

The version 1 controller can use the shared service while returning only the properties supported by its contract.

C#
[HttpGet("{id}")]
public IActionResult GetUser(int id, [FromServices] UserService service)
{
    var user = service.GetUserById(id);

    var response = new
    {
        user.Id,
        user.Name,
        user.Email
    };

    return Ok(response);
}

The version 2 controller can return the additional properties.

C#
[HttpGet("{id}")]
public IActionResult GetUser(int id, [FromServices] UserService service)
{
    var user = service.GetUserById(id);

    return Ok(user);
}

In larger applications, dedicated response DTOs are preferable to anonymous objects because they make API contracts easier to document, test, and maintain.

The important principle is to separate business logic from version-specific request and response models.

Deprecating Older API Versions

Keeping older API versions available forever can increase maintenance costs. Eventually, the development team may need to retire an older version.

Before removing an API version, communicate the change to affected clients.

ASP.NET Core API versioning allows developers to mark an API version as deprecated.

For example:

C#
[ApiController]
[ApiVersion("1.0", Deprecated = true)]
[Route("api/v{version:apiVersion}/users")]
public class UsersV1Controller : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetUser(int id)
    {
        return Ok(new
        {
            Id = id,
            Name = "John",
            Email = "[email protected]"
        });
    }
}

The deprecated version can continue handling requests while clients are given time to migrate.

Deprecation does not automatically remove the endpoint or force clients to upgrade. It communicates the API lifecycle status through the versioning infrastructure.

A practical retirement plan should include usage monitoring, migration documentation, communication, and a clearly defined removal date.

Best Practices for Managing API Versions

Maintain Backward Compatibility

Avoid changing existing API contracts unless there is a clear reason. When a change can break existing clients, introduce a new API version instead.

For mobile applications, consider that users may continue using older releases for an extended period.

Keep Version-Specific Controllers Lightweight

Controllers should primarily handle HTTP requests, validation, and response mapping. Keep database operations and business rules inside shared application services.

This reduces duplication across API versions.

Monitor Older API Usage

Track which API versions are still receiving requests. Useful information includes client application versions, request counts, endpoint usage, and error rates.

Avoid collecting unnecessary personal information when tracking client activity.

Document Every API Version

Maintain clear documentation for request structures, response models, authentication requirements, and deprecated endpoints.

Version-specific Swagger documentation can help developers understand the available API contracts.

Plan API Retirement Carefully

Do not remove an older version simply because a newer version has been released.

Review actual usage and provide clients with enough time to migrate. Communicate breaking changes before retiring an endpoint.

Common Mistakes to Avoid

One common mistake is modifying an existing API response without checking which clients depend on it. Even a small response change can affect applications that expect a specific structure.

Another mistake is creating separate controllers while duplicating the same business logic. This increases maintenance work and can cause inconsistent behavior between versions.

Developers also sometimes assume that marking an API as deprecated automatically disables it. Deprecation is a communication mechanism, not an automatic shutdown process.

Finally, avoid creating a new API version for every minor change. Adding an optional response property or introducing a backward-compatible feature does not always require a new version. Version only when the API contract or behavior changes in a way that existing clients cannot safely handle.

Troubleshooting Common API Versioning Issues

ProblemPossible ReasonSolution
API returns 404Requested version does not match a registered controllerVerify ApiVersion and route configuration
Version parameter is not recognizedIncorrect route constraintUse the apiVersion route constraint
Old clients receive unexpected responsesExisting API contract was modifiedRestore the old contract and introduce a new version
Multiple controllers conflictDuplicate or incorrect version attributesReview controller routes and version declarations
Deprecated version is still accessibleDeprecation does not remove endpointsFollow a planned retirement process

When troubleshooting, check the requested URL, controller version attributes, registered versioning services, and application logs.

Advantages and Disadvantages of API Versioning

Advantages

  • Supports older clients while introducing new API functionality.
  • Reduces the risk of breaking existing mobile and web applications.
  • Allows gradual migration between API versions.
  • Provides clear separation between different API contracts.
  • Makes it easier to plan and communicate breaking changes.

Disadvantages

  • Maintaining multiple versions increases development and testing effort.
  • Older endpoints may require continued security and bug fixes.
  • Documentation becomes more complex as versions increase.
  • Duplicated controllers and business logic can create maintenance problems.
  • API retirement requires communication and careful monitoring.

Summary

API versioning is an important practice for ASP.NET Core applications that support multiple clients with different update schedules. Instead of modifying an existing API and risking compatibility problems, developers can introduce a new version while keeping the previous contract available.

ASP.NET Core supports API versioning through the Asp.Versioning packages, allowing developers to organize endpoints using URL paths, query strings, or HTTP headers.

A maintainable implementation should keep version-specific controllers lightweight, share business logic through services, document API contracts, and monitor older client usage.

Most importantly, API versioning should be used to manage meaningful contract changes rather than every small feature update. With a clear versioning and retirement strategy, development teams can introduce new functionality while keeping existing applications stable.