Api versioning in Asp.Net Core

Bhone Myint Kyaw
2 min readJan 19, 2022

--

Let’s check how we can make the API versioning quick and easy in asp.net core with microsoft.aspnetcore.mvc.versioning.

Api versioning

First, let’s install the required NuGet packages

Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 5.0.0

After that, we need to add some configurations in the program.cs file

builder.Services.AddApiVersioning(options =>{options.AssumeDefaultVersionWhenUnspecified = true;options.DefaultApiVersion = ApiVersion.Default; 
//can set the default api version by using new ApiVersion(1, 0); in the ApiVersion.Default
//(1,0) is equal to 1.0
options.ReportApiVersions = true;
//to get back the available api version in the http response
});

The basic configuration is done and we need to set the API versions in the apicontrollers

[ApiController]public class TestController : ControllerBase{[HttpGet(“api/test/get”)] //default route[ApiVersion(“1.0”, Deprecated = true)] //to informthe api is deprecatedpublic IActionResult getVDefault(){   return Ok(“Default”);}[HttpGet(“api/v{version:apiVersion}/test/get”)] //api with version[ApiVersion(“1.0”, Deprecated = true)]//set current route only accept v1.0public IActionResult getV1(){   return Ok(“Version One”);}[HttpGet(“api/v{version:apiVersion}/test/get”)] [ApiVersion(“2.0”)]//Set current route only accept v2.0 onlypublic IActionResult getV2(){   return Ok(“Version Two”);}}

The controller setup is finished and let’s see how we can make a request to the above controller route from client

Default Route

[HttpGet(“api/test/get”)][ApiVersion(“1.0”, Deprecated = true)]this can be requested by with this formathttp://localhost:007/api/test/get
and we will get the "Default" response

v1 Route

[HttpGet(“api/v{version:apiVersion}/test/get”)] [ApiVersion(“1.0”, Deprecated = true)]this can be requested by with this formathttp://localhost:007/api/v1.0/test/get
and we will get the "Version One" response

v2 Route

[HttpGet(“api/v{version:apiVersion}/test/get”)][ApiVersion(“2.0”)]this can be requested by with this formathttp://localhost:007/api/v2.0/test/get
and we will get the "Version Two" response

I hope you will enjoy this.

--

--

Bhone Myint Kyaw
Bhone Myint Kyaw

Written by Bhone Myint Kyaw

Nerd coder, gamer, 24/7 watching memes

No responses yet