.NET API Versioning Strategies with ASP.NET Core – The Ultimate Guide

API Versioning in ASP.NET Core - Best Strategies & Implementation

Learn how to implement API versioning in ASP.NET Core using URL versioning, query parameters, headers, and media types. Build scalable and maintainable APIs today!


Introduction

Imagine you’ve built a robust API for your application, and it’s gaining traction. But as your application grows, you need to introduce breaking changes. If you modify your existing API endpoints, your older clients will break—resulting in downtime, frustration, and angry users.

This is where API versioning comes in! It allows you to introduce new versions of your API while keeping older versions intact, ensuring smooth transitions for your clients.

In this guide, we’ll explore why API versioning is important, different versioning strategies in ASP.NET Core, and how to implement them step by step.


Why API Versioning Matters in ASP.NET Core?

API versioning is essential for scalability, maintainability, and backward compatibility. Here’s why it’s crucial:

Ensures Backward Compatibility – Older clients can continue using previous versions.
Supports Continuous Development – Allows gradual API improvements without breaking existing apps.
Enhances API Lifecycle Management – Enables deprecation of outdated APIs systematically.
Improves Client Adaptability – Consumers can upgrade at their own pace without disruptions.

Now, let’s dive into different API versioning strategies and their implementation.


Setting Up API Versioning in ASP.NET Core

Step 1: Create a New ASP.NET Core Web API Project

If you don’t already have a project, create one using:

dotnet new webapi -n ApiVersioningDemo
cd ApiVersioningDemo

Step 2: Install API Versioning Package

To enable API versioning, install the Microsoft.AspNetCore.Mvc.Versioning NuGet package:

dotnet add package Microsoft.AspNetCore.Mvc.Versioning

API Versioning Strategies in ASP.NET Core

ASP.NET Core provides multiple ways to handle API versioning:
1️⃣ URL Path Versioning (e.g., /api/v1/products)
2️⃣ Query String Versioning (e.g., /api/products?version=1)
3️⃣ Header Versioning (e.g., api-version: 1)
4️⃣ Media Type Versioning (e.g., Accept: application/vnd.myapi.v1+json)

Let’s implement each method step by step.


1️⃣ URL Path Versioning

How It Works?

The version is specified in the URL itself (e.g., /api/v1/products).

Implementation

Step 1: Enable API Versioning in Program.cs

Modify your Program.cs file to enable API versioning:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;

services.AddControllers();
services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
    options.ApiVersionReader = new UrlSegmentApiVersionReader();
});

var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();

Step 2: Create Versioned Controllers

Create ProductsV1Controller and ProductsV2Controller:

[ApiController]
[Route("api/v{version:apiVersion}/products")]
[ApiVersion("1.0")]
public class ProductsV1Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok(new { Version = "1.0", Message = "Products API - V1" });
}
[ApiController]
[Route("api/v{version:apiVersion}/products")]
[ApiVersion("2.0")]
public class ProductsV2Controller : ControllerBase
{
    [HttpGet]
    public IActionResult Get() => Ok(new { Version = "2.0", Message = "Products API - V2" });
}

Testing URL Path Versioning

Try these requests:

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

Pros: Easy to implement, clear versioning.
Cons: Clutters URLs, forces hardcoded changes in clients.


2️⃣ Query String Versioning

How It Works?

Versioning is done via query parameters (e.g., /api/products?version=1).

Implementation

Modify Program.cs:

options.ApiVersionReader = new QueryStringApiVersionReader("version");

Testing Query String Versioning

GET /api/products?version=1
GET /api/products?version=2

Pros: No change in URL structure.
Cons: Less intuitive, may lead to API abuse.


3️⃣ Header Versioning

How It Works?

Clients specify the API version in the request header:

GET /api/products
Headers: api-version: 1

Implementation

Modify Program.cs:

options.ApiVersionReader = new HeaderApiVersionReader("api-version");

Testing Header Versioning

GET /api/products
Headers:
api-version: 2

Pros: Keeps URLs clean.
Cons: Clients must modify headers explicitly.


4️⃣ Media Type Versioning

How It Works?

Clients specify the version in the Accept header:

GET /api/products
Headers: Accept: application/vnd.myapi.v1+json

Implementation

Modify Program.cs:

options.ApiVersionReader = new MediaTypeApiVersionReader();

Testing Media Type Versioning

GET /api/products
Headers:
Accept: application/vnd.myapi.v2+json

Pros: Follows REST best practices.
Cons: Harder to implement and debug.


Best Practices for API Versioning

🚀 Use Semantic Versioning – Follow major.minor versioning (e.g., v1.1).
🚀 Deprecate Old Versions Gradually – Notify users before removing old APIs.
🚀 Choose the Right Strategy – URL versioning is easy, but header-based is cleaner.
🚀 Document API Changes – Use Swagger (Swashbuckle.AspNetCore) for API documentation.


Conclusion

API versioning is critical for maintaining backward compatibility and ensuring a smooth transition as APIs evolve. In ASP.NET Core, you can choose from URL path, query string, header, and media type versioning—each with its pros and cons.

👉 What’s next?

  • Implement API versioning with Swagger for better documentation.
  • Learn how to deprecate APIs effectively.
  • Explore microservices API gateways like Ocelot for managing API versions at scale.

💬 Have questions? Drop a comment below! 🚀


FAQs

1. Which API versioning strategy is best?

URL path versioning is simple, but header versioning is cleaner. The best choice depends on your use case.

2. Can I combine multiple versioning strategies?

Yes, ASP.NET Core allows multiple versioning strategies simultaneously.

3. How do I document API versions in Swagger?

Use Swashbuckle to display multiple API versions in Swagger UI.

4. Should I deprecate older API versions?

Yes! Clearly mark old APIs as deprecated and provide a migration guide.


🚀 Ready to implement API versioning? Start optimizing your ASP.NET Core APIs today! 🚀

Sandip Mhaske

I’m a software developer exploring the depths of .NET, AWS, Angular, React, and digital entrepreneurship. Here, I decode complex problems, share insightful solutions, and navigate the evolving landscape of tech and finance.

Post a Comment

Previous Post Next Post