Implementing API Versioning in ASP.NET Core Web API

Introduction

As APIs evolve, changes and improvements can lead to breaking changes. API versioning helps maintain backward compatibility while enabling new features. ASP.NET Core provides built-in support for API versioning, making it easy to maintain different API versions efficiently.

In this blog post, I discuss different ways to implement API versioning in ASP.NET Core Web API. Let's start with the first and most important part.

Setting Up API Versioning in ASP.NET Core

To get started, let's first install the required NuGet package:



Once installed, configure API versioning in the Program.cs file:


Implementing Versioned Controllers

Now, let’s create two versions of a ProductsController.

Version 1 (v1) of ProductsController


public class Test

Version 2 (v2) of ProductsController with Additional Data


Testing API Versioning

You can test the API using the following URLs:

  1. Version 1: GET /api/v1/products
  2. Version 2: GET /api/v2/products

Each version returns different responses, ensuring backward compatibility while allowing newer features.

Alternative Versioning Strategies

Besides URL-based versioning, ASP.NET Core supports other approaches:

1. Query String Versioning

Modify Program.cs to use query string versioning:


Call API using:

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

2. Header-Based Versioning

Modify Program.cs to use custom headers:


Set header when calling the API:

GET /api/products
Header: X-API-Version: 1.0

Conclusion

API versioning is crucial for maintaining backward compatibility while allowing improvements in newer versions. ASP.NET Core makes it easy to implement versioning using URL segments, query strings, or headers. By following this approach, you ensure a smooth transition for API consumers as your application evolves.