Authentication-and-Authorization :👈 👉:Encryption and Decryption in .NET

API Versioning in ASP.NET Core

API Versioning in ASP.NET Core

1. Introduction

API Versioning is a technique used to manage changes to an API without breaking existing client applications.

As an application evolves, new requirements may introduce changes such as:

  • Adding new properties to API responses.
  • Removing or renaming existing properties.
  • Changing request formats.
  • Modifying business logic.
  • Introducing new endpoints.
  • Changing validation rules.

These changes can affect applications that already consume the API.

API versioning allows multiple versions of an API to coexist, so existing clients can continue using older versions while new clients use the latest version.

Example:

GET /api/v1/products

Later, a new version is introduced:

GET /api/v2/products

Both versions can operate independently.

2. Table of Contents

  1. Why API Versioning Is Required
  2. Different API Versioning Approaches
  3. Install API Versioning Packages
  4. URL Path Versioning
  5. Query String Versioning
  6. Header Versioning
  7. Media Type Versioning
  8. Configure Multiple Version Readers
  9. Version-Neutral APIs
  10. API Versioning with Swagger
  11. Deprecating Old API Versions
  12. Choosing the Right Versioning Strategy
  13. API Versioning Best Practices
  14. Common API Versioning Mistakes
  15. Interview Questions and Answers
  16. Summary

3. Why API Versioning Is Required

Consider an e-commerce API that initially returns the following product response:

{
    "id": 101,
    "name": "Laptop",
    "price": 55000
}

Several mobile applications and websites consume this API.

Later, the development team decides to change the response:

{
    "productId": 101,
    "productName": "Laptop",
    "pricing": {
        "amount": 55000,
        "currency": "INR"
    }
}

The new response has different property names and a different structure. Existing applications expecting id, name, and price may stop working.

Instead of changing the existing API immediately, introduce a new version.

Version 1

GET /api/v1/products/101
{
    "id": 101,
    "name": "Laptop",
    "price": 55000
}

Version 2

GET /api/v2/products/101
{
    "productId": 101,
    "productName": "Laptop",
    "pricing": {
        "amount": 55000,
        "currency": "INR"
    }
}

This allows old and new applications to work without forcing all clients to upgrade immediately.

4. Different API Versioning Approaches

ASP.NET Core API Versioning supports several approaches.

4.1 URL Path Versioning

The version number is included in the URL path.

GET /api/v1/products
GET /api/v2/products

This is one of the easiest approaches to understand and maintain.

4.2 Query String Versioning

The version number is passed as a query string parameter.

GET /api/products?api-version=1.0
GET /api/products?api-version=2.0

4.3 Header Versioning

The version number is passed through a custom HTTP header.

GET /api/products
api-version: 1.0

The URL remains unchanged, but the request header determines the API version.

4.4 Media Type Versioning

The version is specified through the HTTP Accept header.

GET /api/products
Accept: application/json;v=1.0

This approach uses media type parameters to identify the requested representation.

Comparison of Versioning Approaches

Approach Example Main Advantage
URL path /api/v1/products Easy to understand and test.
Query string ?api-version=1.0 Simple to introduce.
Header api-version: 1.0 Keeps URLs unchanged.
Media type Accept: application/json;v=1.0 Version is associated with representation.

5. Install API Versioning Packages

ASP.NET Core provides API versioning through the Asp.Versioning package ecosystem.

For a typical ASP.NET Core Web API application, install the following packages:

dotnet add package Asp.Versioning.Mvc
dotnet add package Asp.Versioning.Mvc.ApiExplorer

The packages provide the following functionality:

  • Asp.Versioning.Mvc: Provides API versioning support for MVC controllers.
  • Asp.Versioning.Mvc.ApiExplorer: Provides API version information for API exploration tools such as Swagger.

For a Minimal API application, install the appropriate package:

dotnet add package Asp.Versioning.Http

6. URL Path Versioning

URL path versioning is commonly used because the version is clearly visible in the endpoint.

/api/v1/products
/api/v2/products

Step 1: Configure API Versioning

Configure API 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;
        options.ApiVersionReader =
            new UrlSegmentApiVersionReader();
    })
    .AddMvc();
var app = builder.Build();
app.MapControllers();
app.Run();

Explanation

  • DefaultApiVersion: Defines the default API version.
  • AssumeDefaultVersionWhenUnspecified: Uses the default version when a request does not specify one.
  • ReportApiVersions: Adds response headers indicating supported and deprecated API versions.
  • UrlSegmentApiVersionReader: Reads the version from the URL path.
  • AddMvc: Enables API versioning support for MVC controllers.

Note: For a public API, consider requiring clients to specify the version explicitly instead of silently assuming a default.

Step 2: Create Version 1 Controller

using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion(1.0)]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = new[]
        {
            new
            {
                Id = 101,
                Name = "Laptop",
                Price = 55000
            }
        };
        return Ok(products);
    }
}

Step 3: Create Version 2 Controller

using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion(2.0)]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult GetProducts()
    {
        var products = new[]
        {
            new
            {
                ProductId = 101,
                ProductName = "Laptop",
                Pricing = new
                {
                    Amount = 55000,
                    Currency = "INR"
                }
            }
        };
        return Ok(products);
    }
}

Step 4: Test the APIs

Version 1:

GET https://localhost:7001/api/v1/products

Version 2:

GET https://localhost:7001/api/v2/products

Both controllers expose the same logical resource but return different response structures.

7. Query String Versioning

In query string versioning, the version is passed through the URL query string.

Configuration

Change the version reader in Program.cs:

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader =
            new QueryStringApiVersionReader("api-version");
    })
    .AddMvc();

The controller route does not need a version segment:

[ApiController]
[ApiVersion(1.0)]
[Route("api/products")]
public class ProductsV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new
        {
            Id = 101,
            Name = "Laptop"
        });
    }
}

API Requests

GET /api/products?api-version=1.0
GET /api/products?api-version=2.0

The version reader identifies the requested version from the query string.

8. Header Versioning

In header versioning, the client sends the version number in an HTTP header.

Configuration

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader =
            new HeaderApiVersionReader("api-version");
    })
    .AddMvc();

Client Request

GET /api/products
api-version: 1.0

For version 2:

GET /api/products
api-version: 2.0

The controller can use the same route for multiple versions when the actions are mapped to different API versions.

Example

[ApiController]
[ApiVersion(1.0)]
[ApiVersion(2.0)]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    [MapToApiVersion(1.0)]
    public IActionResult GetV1()
    {
        return Ok(new
        {
            Id = 101,
            Name = "Laptop",
            Price = 55000
        });
    }
    [HttpGet]
    [MapToApiVersion(2.0)]
    public IActionResult GetV2()
    {
        return Ok(new
        {
            ProductId = 101,
            ProductName = "Laptop",
            PriceDetails = new
            {
                Amount = 55000,
                Currency = "INR"
            }
        });
    }
}

This approach avoids creating separate controller classes when the differences between versions are limited.

9. Media Type Versioning

Media type versioning uses the HTTP Accept header to specify the required API version.

Configuration

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader =
            new MediaTypeApiVersionReader();
    })
    .AddMvc();

Client Request

GET /api/products
Accept: application/json;v=1.0

For version 2:

GET /api/products
Accept: application/json;v=2.0

The media type version reader extracts the version from the Accept header.

This approach can be useful when API versions represent different resource representations. However, clients and API documentation must clearly communicate the expected media type.

10. Configure Versioning with Multiple Readers

An API can accept more than one versioning mechanism.

For example, it can support both URL path and header versioning.

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader =
            ApiVersionReader.Combine(
                new UrlSegmentApiVersionReader(),
                new HeaderApiVersionReader("api-version")
            );
    })
    .AddMvc();

Important: When multiple readers are combined, the request must not provide conflicting version values. A request containing different versions in the URL and header can result in an ambiguous API version error.

Use multiple readers only when there is a clear compatibility requirement. Supporting several mechanisms unnecessarily can make API usage and troubleshooting more complicated.

11. Version-Neutral APIs

Some APIs do not need version-specific behavior.

Examples include:

  • Health check endpoints.
  • Basic status endpoints.
  • Certain monitoring endpoints.

Use [ApiVersionNeutral] to indicate that an endpoint is not associated with a particular API version.

using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersionNeutral]
[Route("api/health")]
public class HealthController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new
        {
            Status = "Healthy"
        });
    }
}

A version-neutral endpoint is not restricted to a particular API version.

12. API Versioning with Swagger

Swagger provides interactive API documentation.

When an application supports multiple API versions, it is useful to generate separate Swagger documents for each version.

Install Swagger Package

Install the Swagger package if it is not already installed:

dotnet add package Swashbuckle.AspNetCore

Configure API Explorer

using Asp.Versioning;
using Asp.Versioning.ApiExplorer;
builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.ReportApiVersions = true;
        options.ApiVersionReader =
            new UrlSegmentApiVersionReader();
    })
    .AddMvc()
    .AddApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
    });

Configure Swagger Documents

The following is a simplified setup for generating Swagger documents from discovered API versions:

using Asp.Versioning.ApiExplorer;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
    .AddApiVersioning()
    .AddMvc()
    .AddApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
    });
builder.Services.AddSwaggerGen();
var app = builder.Build();
var apiVersionDescriptionProvider =
    app.Services.GetRequiredService<IApiVersionDescriptionProvider>();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
    foreach (var description in
        apiVersionDescriptionProvider.ApiVersionDescriptions)
    {
        options.SwaggerEndpoint(
            $"/swagger/{description.GroupName}/swagger.json",
            description.GroupName.ToUpperInvariant());
    }
});
app.MapControllers();
app.Run();

Important: The simplified example shows version discovery and Swagger UI registration. A complete Swashbuckle setup must also register a Swagger document for each discovered version and configure an appropriate document inclusion strategy. Registering AddSwaggerGen() alone does not create all versioned JSON documents.

The expected Swagger UI experience is separate documentation entries such as:

Swagger UI
    v1
        GET /api/v1/products
    v2
        GET /api/v2/products

13. Deprecating Old API Versions

When a new API version is introduced, the old version should not necessarily be removed immediately.

Existing applications may still depend on it.

A better approach is to mark the older version as deprecated and communicate a migration timeline.

Example: Deprecated Version 1

[ApiController]
[ApiVersion(1.0, Deprecated = true)]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new
        {
            Message = "This API version is deprecated."
        });
    }
}

Version 2 Remains Active

[ApiController]
[ApiVersion(2.0)]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new
        {
            Message = "This API version is supported."
        });
    }
}

When ReportApiVersions is enabled, API version response headers can identify supported and deprecated versions.

api-supported-versions: 2.0
api-deprecated-versions: 1.0

These headers help clients identify which versions are available and which versions are scheduled for retirement.

Deprecation vs Retirement vs Removal

  • Deprecation: The version is still available but should no longer be used for new development.
  • Retirement: The version is no longer supported.
  • Removal: Requests to that version will no longer work.

Communicate retirement dates, migration instructions, and breaking changes before removing an API version.

14. Choosing the Right Versioning Strategy

The best approach depends on the API's consumers, architecture, and compatibility requirements.

Situation Recommended Approach
Public REST API URL path versioning
API with simple client integration URL path versioning
Existing system requires unchanged URLs Header versioning
Version-specific representations Media type versioning
Simple internal API URL path or query string
Multiple client applications Explicit versioning with a migration plan

Practical recommendation: URL path versioning is a good default for many public and enterprise REST APIs because the version is visible, easy to test, and straightforward to document.

15. API Versioning Best Practices

15.1 Introduce New Versions Only for Meaningful Changes

Do not create a new API version for every small implementation change.

Adding an optional response property may be backward-compatible for well-designed clients. Removing or renaming a property is generally a breaking change.

15.2 Maintain Backward Compatibility

Avoid changing existing API behavior unexpectedly.

For example, do not change:

{
    "status": "success"
}

to:

{
    "status": true
}

without considering the impact on existing clients.

15.3 Use a Consistent Versioning Strategy

Avoid using URL versioning for some endpoints, header versioning for others, and query string versioning for unrelated endpoints without a strong reason.

Consistency makes APIs easier to understand and maintain.

15.4 Maintain a Deprecation Policy

Define the following:

  • How long old versions remain available.
  • How clients are notified.
  • When support ends.
  • How migration is handled.

15.5 Keep Business Logic Shared

Do not duplicate the entire business logic for every API version.

Use separate request and response DTOs when necessary, but share application services and domain logic wherever the business behavior is the same.

Example Architecture

API Version 1 API Version 2 ProductsV1Controller ProductsV1Response ProductService ProductRepository ProductsV2Controller ProductsV2Response ProductService ProductRepository

Controllers translate version-specific requests and responses while the application service contains reusable business operations.

15.6 Test Every Supported Version

When introducing a new version, verify that older versions continue to work.

Include:

  • Unit tests.
  • Integration tests.
  • Contract tests.
  • Authentication and authorization tests.
  • Error response tests.

15.7 Document Breaking Changes

Provide clear documentation describing:

  • Changed properties.
  • Removed endpoints.
  • New validation rules.
  • Updated request formats.
  • Migration instructions.

15.8 Monitor Usage of Old Versions

Track API requests by version.

This helps identify clients still using older versions and allows the team to plan retirement based on actual usage.

16. Common API Versioning Mistakes

Mistake Why It Is a Problem
Creating a new version for every minor change Increases maintenance overhead.
Removing old versions immediately Breaks existing clients.
Duplicating all business logic Creates code duplication.
Using inconsistent versioning approaches Confuses API consumers.
Not documenting breaking changes Makes migration difficult.
Not testing older versions Existing clients may break.
Keeping deprecated versions indefinitely Increases maintenance and security overhead.
Assuming every response change is breaking Creates unnecessary versions.
Not monitoring version usage Makes retirement decisions difficult.

17. Interview Questions and Answers

Q1. What is API Versioning?

API versioning is a technique used to manage changes to an API while maintaining compatibility with existing clients.

It allows multiple versions of an API to operate simultaneously.

Q2. Why do we need API Versioning?

We need API versioning when an API undergoes breaking changes, such as removing properties, renaming fields, changing request formats, or modifying endpoint behavior.

It prevents existing client applications from breaking unexpectedly.

Q3. What are the different types of API Versioning?

The commonly used approaches are:

  1. URL path versioning.
  2. Query string versioning.
  3. Header versioning.
  4. Media type versioning.

Q4. Which API Versioning approach is best?

There is no universally best approach.

URL path versioning is often preferred for public and enterprise APIs because it is simple, visible, and easy to document.

Q5. How do you implement API Versioning in ASP.NET Core?

Install the Asp.Versioning.Mvc package, configure API versioning in Program.cs, and use attributes such as [ApiVersion] and [MapToApiVersion] on controllers and actions.

Q6. What is the difference between [ApiVersion] and [MapToApiVersion]?

  • [ApiVersion]: Declares the versions supported by a controller.
  • [MapToApiVersion]: Maps a particular action to a specific API version.

Q7. Can multiple API versions exist in the same ASP.NET Core application?

Yes. Multiple controllers or actions can support different API versions within the same application.

Q8. What is a deprecated API version?

A deprecated API version is still available but is no longer recommended for new development.

Clients should migrate to a supported version before the deprecated version is retired.

Q9. How do you avoid duplicating business logic across API versions?

Use shared application services and domain logic. Keep version-specific request and response DTOs in their respective API layers.

Q10. How do you handle API versioning in microservices?

Each microservice can manage its own API versions based on its consumer requirements.

An API gateway can route requests to appropriate services, but version compatibility should be managed by the owning service.

Q11. What happens when a client requests an unsupported API version?

The API versioning framework generally returns an HTTP 400 Bad Request response when the supplied version is invalid or unsupported. Exact behavior can depend on the configuration and endpoint mapping.

Q12. Is API Versioning mandatory in ASP.NET Core?

No. It is not mandatory for every application.

However, it is useful for APIs consumed by multiple clients or external systems, especially when backward compatibility is important.

Q13. What is the difference between API Versioning and Assembly Versioning?

API versioning manages the public HTTP contract exposed to API consumers.

Assembly versioning identifies versions of compiled .NET assemblies.

They solve different problems and do not need to change together.

Q14. How do you manage API versions in Swagger?

Use Asp.Versioning.Mvc.ApiExplorer to discover API versions and configure Swagger to generate separate documentation for each version.

Q15. Should every API change require a new version?

No. Only changes that require a different API contract or introduce incompatible behavior generally need a new version.

Backward-compatible changes can often be introduced without creating another version.

18. Summary

API Versioning helps ASP.NET Core applications evolve without unnecessarily breaking existing clients.

The key points are:

  • API versioning supports multiple API contracts.
  • URL path, query string, header, and media type are common versioning approaches.
  • Asp.Versioning.Mvc provides versioning support for MVC controllers.
  • [ApiVersion] identifies supported versions.
  • [MapToApiVersion] maps actions to specific versions.
  • [ApiVersionNeutral] identifies endpoints that are not tied to a particular version.
  • Swagger can provide separate documentation for each API version.
  • Deprecated versions should have a clear migration and retirement policy.
  • Business logic should be shared wherever possible to avoid duplication.

19. Conclusion

API Versioning is an important part of designing maintainable and backward-compatible REST APIs.

In real-world ASP.NET Core applications, a consistent versioning strategy, shared business logic, version-specific DTOs, automated testing, and a clear deprecation policy help teams evolve APIs safely while supporting existing consumers.

=====================================================================================================================

API versioning in ASP.NET Core is a strategy for managing changes to your API over time while maintaining backward compatibility for existing clients. This allows you to introduce new features, modify existing functionality, or restructure your API without breaking applications that rely on older versions.

Why Versioning is Needed

  • Backward Compatibility: Ensures that older client applications continue to function correctly even after significant changes are introduced in newer API versions.
  • Controlled Evolution: Allows for gradual updates and enhancements to the API, preventing a complete overhaul that could disrupt all clients simultaneously.
  • Client Flexibility: Provides clients with the option to upgrade to newer versions at their own pace, rather than being forced to adopt changes immediately.

Common REST API Versioning Strategies

1. URL-based Versioning

The API version is included directly in the URL path (e.g., /api/v1/products, /api/v2/products).

  • Format: /api/v1/resource
  • Pros: Easy to implement and understand; visible in logs and browser.
  • Cons: Can clutter the URI space; not ideal for hypermedia-driven APIs.

2. Header-based Versioning

The API version is sent in a custom request header (e.g., X-API-Version: 1.0).

  • Format: Accept: application/vnd.myapi.v1+json
  • Pros: Keeps URLs clean; aligns with content negotiation.
  • Cons: Harder to test/debug; less visible to consumers.

3. Query Parameter Versioning

The API version is specified as a query parameter (e.g., /api/products?api-version=1.0).

  • Format: /api/resource?version=1
  • Pros: Simple to implement; flexible.
  • Cons: Not RESTful by strict standards; can be overlooked by caching proxies.

4. Custom Request Header

  • Format: X-API-Version: 1
  • Pros: Clean separation of concerns.
  • Cons: Requires clients to explicitly set headers; not self-documenting.

5. Media Type Versioning

The API version is embedded within the Accept header's media type (e.g., Accept: application/vnd.yourcompany.product-v1+json).

Implementation Steps in ASP.NET Core

  • Install the Microsoft.AspNetCore.Mvc.Versioning NuGet package.
  • Configure API Versioning in Startup.cs (or Program.cs for .NET 6+):

public void ConfigureServices(IServiceCollection services)
{
    services.AddApiVersioning(options =>
    {
        options.ReportApiVersions = true;
        options.AssumeDefaultVersionWhenUnspecified = true;
        options.DefaultApiVersion = new ApiVersion(1, 0);
    });
}

Define Versioned Controllers


[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV1Controller : ControllerBase
{
    // ... actions for API version 1.0
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
[ApiController]
public class ProductsV2Controller : ControllerBase
{
    // ... actions for API version 2.0
}
  • Configure Routing: Ensure your routes correctly map to the versioned controllers based on your chosen strategy (e.g., using v{version:apiVersion} in the route template for URL-based versioning).

By implementing API versioning, you can effectively manage the evolution of your RESTful APIs in ASP.NET Core, ensuring a smooth experience for both new and existing clients.

Best Practices

  • Deprecate gracefully: Provide clear documentation and sunset timelines.
  • Semantic versioning: Use major versions for breaking changes.
  • Automated testing: Ensure older versions remain functional.
  • Documentation: Maintain version-specific docs for clarity.

Versioning is a strategic decision—URI versioning is often preferred for public APIs due to its simplicity and visibility, while header-based approaches suit internal or hypermedia APIs better.

🔙
Authentication-and-Authorization :👈 👉:Encryption and Decryption in .NET