API versioning .net 6 C#

Çağdaş Erman Afacan
2 min readDec 8, 2022

--

API versioning is a technique for creating and maintaining multiple versions of an API so that different clients can use the version of the API that is most suitable for their needs. This is often done to ensure backward compatibility, add new features, or make breaking changes to the API without affecting existing clients.

To use API versioning in .NET 6, you can use the Microsoft.AspNetCore.Mvc.Versioning package, which provides a set of attributes and classes that you can use to specify and handle API versions in your ASP.NET Core Web API project. Here is an example of how to use API versioning in .NET 6:

// Add the API versioning package to the project
// using the dotnet add package command
dotnet add package Microsoft.AspNetCore.Mvc.Versioning

// In the ConfigureServices method of the Startup class,
// add the API versioning services to the service container
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddApiVersioning();
}

// In the controller, use the ApiVersion attribute
// to specify the supported API versions
[ApiVersion("1.0")]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ValuesController : ControllerBase
{
// Use the MapToApiVersion attribute
// to specify the API version for each action
[HttpGet]
[MapToApiVersion("1.0")]
public ActionResult<IEnumerable<string>> GetV1()
{
return new string[] { "value1", "value2" };
}

[HttpGet]
[MapToApiVersion("2.0")]
public ActionResult<IEnumerable<string>> GetV2()
{
return new string[] { "value1", "value2", "value3" };
}
}

In the example above, the ApiVersion attribute is used to specify the supported API versions for the ValuesController class. The MapToApiVersion attribute is used to specify the API version for each action in the controller. The AddApiVersioning method is used to add the API versioning services to the service container in the ConfigureServices method of the Startup class.

When a client makes a request to the API, it can specify the API version in the api-version query string parameter or in the Accept header of the request. The API versioning middleware will then route the request to the appropriate action based on the specified API version.

For more information about using API versioning in .NET, see the .Net Core API versioning documentation.

--

--