.NET Framework .NET C# VB.NET LINQ ASP.NET Web API REST SignalR Windows Forms WPF WCF RabbitMQ PHP SQL Server MySQL PostgreSQL MariaDB SQLite MongoDB ADO.NET ORM Entity Framework Dapper XML JSON HTML5 CSS3 Bootstrap JavaScript jQuery Angular React TypeScript NPM Blazor UI/UX Responsive Web Design Redis Elasticsearch GraphQL Grafana Agile Scrum Kanban Windows Server IIS PowerShell Active Directory TFS Azure Automation Software Reverse Engineering Performance Optimization Git Jira/Confluence CI/CD TeamCity SOLID KISS DRY YAGNI
Always will be ready notify the world about expectations as easy as possible: job change page

How to implement API Versioning in ASP.NET Core

Добавлено: Sep 10, 2023
Автор: Sriram Kumar Mannava
Источник: источник
Просмотров: 118

API Versioning in ASP.NET Core

In a situation where we need to modify our API’s structure or functionality while ensuring that existing API clients remain unaffected, the solution is versioning.

We can designate our current APIs as the older version and introduce all intended changes in the next (or latest) version. This approach resolves two key issues:

1. Backward compatibility is maintained as the current APIs continue to coexist. This ensures that our clients won’t encounter any problems.

2. We gain the ability to offer optional functionalities to clients through different versions. Clients can choose a particular version to access new or improved features without disrupting their existing setup.

Things to keep in mind while Versioning

When adding versioning to our APIs, we need to check three things:

1. Ensure the system can understand the requested version.
2. Confirm that requests are directed to the appropriate versioned endpoints, like sending v2 requests to v2 endpoints.
3. Decide on the best method to include version information in the requests.

In ASP.NET Core, versioning APIs is made easy thanks to the support provided by the API Versioning library for ASP.NET Core.

We implement the API versioning mechanism in 3 steps:

Install Nuget Package

dotnet add package Microsoft.AspNetCore.Mvc.Versioning

Register API Versioning service

Include the API Versioning service in the IServiceCollection to enable it to detect and direct requests according to their version.

public void ConfigureServices(IServiceCollection services)
    services.AddScoped<IHeroesRepository, HeroesRepository>();
    services.AddApiVersioning(setup =>
        setup.DefaultApiVersion = new ApiVersion(1, 0);
        setup.AssumeDefaultVersionWhenUnspecified = true;
        setup.ReportApiVersions = true;

Modify API Controller

We label the API Controller with the version numbers it uses when a request for that specific version is made.

namespace Heroes.Api.Controllers.V2
    [Route("api/[controller]")] // for backward compatibility
    public class HeroesController : ControllerBase
        // heroes CRUD operations

The [ApiVersion] indicates which version the controller corresponds to, using the version specified in the route as ‘v{version:apiVersion.’ This includes the version number in the route when matching requests.

For example, both ‘/api/v1.0/heroes/1’ and ‘/api/v1/heroes/1’ match this controller. API versions can have major and minor components. Sometimes, the minor part is omitted, leaving it up to the developers to specify.

When we use both [Route(“api/v{version:apiVersion}/[controller]”)] and [Route(“api/[controller]”)] on a controller, we ensure support for requests from older route templates. This is important for compatibility with older route paths, ensuring both ‘/api/v1/heroes/1’ and ‘/api/heroes/1’ are handled by the mentioned controller.

To introduce a new version of the same controller with additional features or changes, we create a new controller (or extend the current one if no changes are needed) and assign it the next version number.

How do we pass the Version Information?

There are various approaches to pass version information to the API when requesting data.

via URL Segment

The default method is the URL Segment approach, where we put the version info in the URL path. The ASP.NET Core ApiVersion service checks the path for this version and decides which controller to use for the request.

Big API providers like Google and Facebook also use URL Segments to pick the API version. To set this explicitly, we choose it as the ApiVersionReader like this:

services.AddApiVersioning(setup =>
    setup.ApiVersionReader = new UrlSegmentApiVersionReader());

via Query

In this method, the version is added to the URL as a query parameter. The benefit is that the URL remains neat, and we can change the version by adjusting the query parameter.

However, the downside is that if we modify the version number, we must update it in all URLs with the query parameters.

To use query parameter-based versioning, we set up the QueryStringApiVersionReader in the AddApiVersioning() function.

By default, the version is sent using the “api-version” query parameter, but we can change it by specifying a different parameter name in the QueryStringApiVersionReader’s constructor.

For example, AWS APIs use this method to specify the version of the service to invoke through the query parameter.

// /api/heroes/?api-version=2.0 - default
    options => options.ApiVersionReader = new QueryStringApiVersionReader());

// /api/heroes/?v=2.0
    options => options.ApiVersionReader = new QueryStringApiVersionReader("v"));

via Header

The third method uses request headers to convey version information, keeping the URL clean and constant. The version to map is decided based on the request header.

To enable this, we use the HeaderApiVersionReader as the ApiVersionReader to look for version details in the headers.

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

via Content Type

The fourth method uses expanded media types in request headers to communicate version details. To do this, we use ApiVersionReader with an instance of MediaTypeApiVersionReader().

By default, the version is sent as “v={versionNumber},” but we can change this by specifying the desired key in the constructor, similar to how we customize QueryStringApiVersionReader().

// Content-Type: application/json;v=2.0 - default
    options => options.ApiVersionReader = new MediaTypeApiVersionReader());
// Content-Type: application/json;version=2.0
    options => options.ApiVersionReader = new MediaTypeApiVersionReader("version"));

Reading from More than one Sources

Sometimes, we might want to get version information from different sources instead of sticking to one method all the time. In those situations, we can use multiple ApiVersionReader instances, as shown below.

services.AddApiVersioning(setup =>
    setup.ApiVersionReader = ApiVersionReader.Combine(
    new UrlSegmentApiVersionReader(),
    new HeaderApiVersionReader("api-version"),
    new QueryStringApiVersionReader("api-version"),
    new MediaTypeApiVersionReader("version"));


API versioning is used when you need to modify your API’s structure or functionality while ensuring existing clients are not affected. It allows you to maintain backward compatibility and offer optional features through different versions.
Some key considerations you may need to make — Ensure the system can understand the requested version. Confirm that requests are routed to the correct versioned endpoints. Decide how to include version information in requests.

ASP.NET Core provides support for API versioning through the API Versioning library.

You will follow these implementation steps
1. Install the required NuGet package.
2. Register the API Versioning service in the IServiceCollection to enable version detection and routing.
3. Label your API Controllers with version numbers to specify which version they correspond to.

Version information can be passed in various ways — URL Segment, Query Parameters, Headers, Content Type. In some cases, you may need to retrieve version information from multiple sources. You can achieve this by using multiple instances of ApiVersionReader.

Feb 17, 2023
Author: Juldhais Hengkyawan
A Guide to Building Scalable, Maintainable Web API using ASP .NET CoreThe term “Clean Architecture” has become increasingly popular in software development in recent years. Clean Architecture is a software design pattern that prioritizes the separation of concerns, making it...
Aug 23, 2022
Author: Luis Rodrigues
Suppose we are building a web api that contains a route to send notification messages to other systems.For security matters, before sending any notification message, we need to provide some credentials to these systems to they accept our messages.However, these...
Aug 22, 2021
The following are a set of best practices for using the HttpClient object in .NET Core when communicating with web APIs. Note that probably not all practices would be recommended in all situations. There can always be good reasons to...
Jan 2, 2023
Author: Jaydeep Patil
In this article, we are going to discuss the working of CQRS and MediatR patterns and step-by-step implementation using .NET Core 6 Web API.Agenda Introduction of CQRS Pattern When to use CQRS ...
Написать сообщение

© 1999–2023 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET | .NET Core | C# | ASP.NET | Windows Forms | WPF | Windows Phone | HTML5 | CSS3 | jQuery | AJAX | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban
GitHub profile