joydip_kanjilal
Contributor

Advanced API versioning in ASP.NET Core Web API

how-to
Aug 26, 20194 mins
APIsMicrosoft .NETSoftware Development

Take advantage of API versioning in ASP.NET Core to maintain multiple versions of the same API.

binary code matrix
Credit: Carlos Castilla / Getty Images

API versioning in a Web API lets you preserve multiple versions of the same API while at the same time keep the same URI as much as possible. With ASP.NET Core, API versioning has been made much easier.

One objective of Web API is to serve multiple clients, whether based on homogenous or heterogenous platforms. Because you might have several clients using an API, upgrading an API while at the same time maintaining support for the previous versions is a challenge. You might have a few users who would like to use the old API. That’s exactly where API versioning fits in.

When building RESTful services, it is imperative that you have a versioning strategy in place so that you can maintain multiple versions of the API. You should ensure that genuine calls to your API doesn’t get rejected due to the versioning policy that you have defined. You should take a look at the versioning semantics outlined in the Microsoft REST API guidelines

Create an ASP.NET Core API project

First, let’s create an ASP.NET Core project in Visual Studio. With Visual Studio 2017 or 2019 is installed in your system, follow the steps outlined below to create a new ASP.NET Core project in Visual Studio:

  1. Launch the Visual Studio IDE.
  2. Click Create New Project.
  3. In the Create New Project window, select ASP.NET Core Web Application from the list of the templates.
  4. Click Next.
  5. In the Configure Your New Project window that appears, specify the name and location for the new project.
  6. Click Create.
  7. A new window, Create New ASP.NET Core Web Application, appears.
  8. Select .NET Core as the runtime and ASP.NET Core 2.2 (or later) from the dropdown list at the top.
  9. Select API as the project template to create a new ASP.NET Core API application.
  10. Ensure that the check boxes Enable Docker Support and Configure for HTTPS are unchecked, because you won’t be using those features here.
  11. Ensure that Authentication is set to No Authentication, because you won’t be using authentication either.
  12. Click Create.

This creates a new ASP.NET Core API project in Visual Studio.

Install the NuGet package

Now that you have created an ASP.NET Core API project in Visual Studio, install the necessary NuGet Package. To do this, select the project in the Solution Explorer Window, right-click it, and then select Manage NuGet Packages in the contextual menu that appears. Then install the following package from the NuGet Package Manager: Microsoft.AspNetCore.Mvc.Versioning.

Alternatively, you can install the package from the NuGet Package Manager Console by typing the following command.

Install-Package Microsoft.AspNetCore.Mvc.Versioning

Enable API versioning

So far so good. To enable API versioning, add a call to the AddApiVersioning method in the ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddApiVersioning();
        } 

You need the following namespace to be included: Microsoft.AspNetCore.Mvc.Versioning.

You can specify default versioning as well:

    public void ConfigureServices(IServiceCollection services) 
    { 
        services.AddMvc(); 
        services.AddApiVersioning(v => 
        { 
            v.ReportApiVersions = true; 
            v.AssumeDefaultVersionWhenUnspecified = true; 
            v.DefaultApiVersion = new ApiVersion(1, 0); 
        }); 
    }

Versioning using QueryString Parameter

Consider the following API:

[ApiVersion("2.0")]
 [Route("api/[controller]")]
 [ApiController]
 public class ValuesController : ControllerBase
 {
     [HttpGet]
     public ActionResult<IEnumerable<string>> Get()
     {
         return new string[] { "value1", "value2" };
     }
   //API methods
 }

You can access this API using this URL: https://localhost:51868/api/values?api-version=2.0.

Replace the port number with the port number at which this API runs using IIS Express in your system.

Versioning using routes

In route-based versioning, you should specify the version of the API in the URL. consider the following API. Note how the route has been specified to include versioning.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<string> Get()
    {
       return "Hello World";
    }
}

Next, you can access the Get method of this API using the following URL: https://localhost:51868/api/v1.0/values.

Ignore API versioning

You might have some APIs that need just one version. For such APIs, you might want to ignore API versioning using the [ApiVersionNeutral] attribute as shown here:

[ApiVersionNeutral]
 [Route("api/[controller]")]
 [ApiController]
 public class HomeController : ControllerBase
 {
      [HttpGet]
      public ActionResult<string> Get()
      {
          return "ApiVersionNeutral attribute demo.";
      }
 }
joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author