Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Sep 10, 2023

How to implement API Versioning in ASP.NET Core

Автор:
Sriram Kumar Mannava
Источник:
Просмотров:
1179

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.AddControllers();
 
    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
{
    [ApiController]
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [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
services.AddApiVersioning(
    options => options.ApiVersionReader = new QueryStringApiVersionReader());

// /api/heroes/?v=2.0
services.AddApiVersioning(
    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.

services.AddApiVersioning(
    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
services.AddApiVersioning(
    options => options.ApiVersionReader = new MediaTypeApiVersionReader());
// Content-Type: application/json;version=2.0
services.AddApiVersioning(
    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"));
});

Summary

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.

Похожее
Jul 26, 2023
Author: Jason Watmore
Built with .NET 7.0, Dapper 2.0 and PostgreSQLIn this tutorial we'll show how to build a .NET 7.0 (ASP.NET Core) API with Dapper and PostgreSQL that supports CRUD operations.Tutorial contents Example API overview Tools...
Aug 15, 2023
Whether you have an app with just a few users or millions of users per day, like Agoda, improving the user experience by optimizing application performance is always crucial.In the case of very high-traffic websites in the cloud, this optimization...
Dec 20, 2023
Author: Fiodar Sazanavets
You can run a single monolithic instance of a server application only if the number of clients accessing your application doesn’t exceed a couple of thousand. But what if you expect hundreds of thousands, or even millions, of clients to...
May 2
Author: Ankit Sahu
IntroductionCreating a CRUD (Create, Read, Update, Delete) API in .NET 8 with an In-memory collection is a common scenario in web development. In this article, we’ll walk through building a complete .NET 8 Web API with a real-world use case.PrerequisitesVisual...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | 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