Pro Code Guide

Developer’s Guide To Programming

HOME    CONTACT   ABOUT

How to Implement Web API Versioning in ASP.NET Core – Detailed Guide

Updated Feb 2, 2021 | 0 comments

Web API versioning though being one of the important features mostly goes ignored when building a Web API application. Web API versioning in ASP.NET Core is simple and easy to implement. In this article, we will look at what is Web API versioning along with why it is needed and how to achieve versioning in ASP.NET Core.

Web API Versioning – What & Why?

Web API Versioning in ASP.NET Core

When we start a new Web API project at that time it is all fine as we develop an initial version get it tested with all the clients and push it to production. Now after going to production, there are some changes in the existing Web API which is a mandatory change for one of the clients but it will not be possible for other clients to go live with new changes at the same time.

It is not recommended to change existing working clients by implementing new Web API features which they don’t need. So now if you change the existing Web API on production with breaking changes and if any of the clients don’t implement new changes it will start failing. So now there is a need to support the old version as well as the newer version of Web API so that all existing clients can function without failing.

API versioning is a feature using which we can implement multiple versions of the same API so that different clients can work with the required version of API.

ASP.NET Core 5 Design Patterns: Thinking code using architectural principles, testing, design patterns, and C

Implement Web API versioning in ASP.NET Core

There are many ways to implement versioning in Web API. Here I will be covering methods to version Web API using Nuget Package Microsoft.AspNetCore.Mvc.Versioning

We can achieve Web API versioning using following approaches

  1. Query String
  2. HTTP Header
  3. URL

Here for demonstration purposes, I have created an ASP.NET Core 3.1 Web API project. I will be using the default generated WeatherForecast Controller for configuring Web API Versioning. By default, there is no versioning support added as shown below.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    [HttpGet]
    public string Get()
    {
        return "This is from WeatherForecast - Sunny Day";
    }
}

As shown below Install the Nuget package and enable the support for Web API versioning in ConfigureServices method in the startup.cs file.

Web API Versioning in ASP.NET Core 3
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApiVersioning(apiVerConfig =>
        {
            apiVerConfig.AssumeDefaultVersionWhenUnspecified = true;
            apiVerConfig.DefaultApiVersion = new ApiVersion(new DateTime(2020, 6, 6));
        });

        services.AddControllers();
    }
    //Remaining code has been removed
}

Web API Versioning using Querystring Parameter

Here you need to define the same controller twice with different values for ApiVersion attribute in different namespaces as shown below.

namespace WebAPIVersioning.Controllers.V1
{
    [ApiVersion("1.0")]
    [Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V1 - Sunny Day";
        }
    }
}

namespace WebAPIVersioning.Controllers.V2
{
    [ApiVersion("2.0")]
    [Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V2 - Rainy Day";
        }
    }
}

After defining multiple versions of the same controller as shown above you can invoke these using version number in querystring i.e. http://server:port/api/weatherforecast?api-version=1.0 or 2.0.

Below is the output screen from both version of API

Versioning Using Querystring

Web API Versioning using HTTP Header

For version to be part of HTTP header and enable controllers to read version number form header you need to first configure this in ConfigureServices method in startup.cs file as hows below

public void ConfigureServices(IServiceCollection services)
{
    services.AddApiVersioning(apiVerConfig =>
    {
        apiVerConfig.AssumeDefaultVersionWhenUnspecified = true;
        apiVerConfig.DefaultApiVersion = new ApiVersion(1,0);
        apiVerConfig.ReportApiVersions = true;
        apiVerConfig.ApiVersionReader = new HeaderApiVersionReader("api-version");
    });

    services.AddControllers();
}

Then you need to define the same controller twice with different values for ApiVersion attribute in different namespaces as shown below.

namespace WebAPIVersioning.Controllers.V1
{
    [ApiVersion("1.0")]
    [Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V1 - Sunny Day";
        }
    }
}

namespace WebAPIVersioning.Controllers.V2
{
    [ApiVersion("2.0")]
    [Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V2 - Rainy Day";
        }
    }
}

After defining multiple versions of the same controller as shown above you can invoke these using version number in HTTP header as “api-version: 1.0” or “api-version: 2.0”

Below is the output screen from both version of API

Versioning Using HTTP Header

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

Web API Versioning using URL

Here you need to define the same controller twice with different values for ApiVersion attribute in different namespaces as shown below. Also, you need to add parameter v{version:apiVersion} in route attribute like Route(“api/v{version:apiVersion}/[controller]”) so that API version becomes part of URL.

namespace WebAPIVersioning.Controllers.V1
{
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V1 - Sunny Day";
        }
    }
}

namespace WebAPIVersioning.Controllers.V2
{
    [ApiVersion("2.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V2 - Rainy Day";
        }
    }
}

After defining multiple versions of the same controller as shown above you can invoke these using version number in HTTP URL i.e. http://server:port/api/v1/weatherforecast or http://server:port/api/v2/weatherforecast

Below is the output screen from both version of API

Versioning in ASP.NET Core using HTTP URL

Supported & Deprecated API Version

In startup.cs file while configuring API version since we have enabled parameter ReportApiVersions so any API call will return supported versions for that API in response header as shown below.

Supported API Versions

Now if you want to pass on the information that older version of API will be removed then you can add deprecate flag to the version of API which will be not supported in future.

namespace WebAPIVersioning.Controllers.V1
{
    [ApiVersion("1.0",Deprecated = true)]
    [Route("api/[controller]")]
    [ApiController]
    public class WeatherForecastController : ControllerBase
    {
        [HttpGet]
        public string Get()
        {
            return "This is from WeatherForecast V1 - Sunny Day";
        }
    }
}
deprecated API versions

Summary

API versioning is useful when you need to enhance an existing API that is being consumed by multiple clients. Versioning in ASP.NET Core Web API is easy and simple to implement. We can make use of the NuGet package Microsoft.AspNetCore.Mvc.Versioning to achieve the same.

Though there are a number of ways to achieve API versioning I personally prefer URL based versioning as that avoids extra api-version parameter in querystring and HTTP header both.

You can also check my other article on Top 12 ASP.NET Core libraries for developers: https://procodeguide.com/programming/top-12-essential-asp-net-core-libraries/

Hope you found this article useful. Your support is appreciated!
Buy me a coffeeBuy me a coffee
Home 9 Programming 9 How to Implement Web API Versioning in ASP.NET Core – Detailed Guide

Set start URL in ASP.NET Core – Quick & Easy ways

This article will cover the ways to set start URL in ASP.NET Core 5 applications i.e. change the default URL (http://localhost:5000) in ASP.NET Core applications. When you create any new ASP.NET Core application whether its MVC App or Web API and run it then it will...

Hangfire in ASP.NET Core – Easy way to Schedule Background Jobs

This article covers detail about how to integrate Hangfire in ASP.NET Core applications which is an easy way to schedule background jobs in .NET Core and .NET based applications. Background jobs or tasks allow the programmers to execute code on a different thread but...

How to Send Emails in ASP.NET Core – Quick & Easy Guide

These days sending emails like user email id confirmation, OTP emails, acknowledgments, etc. is a very common requirement of any application. In this article, we will see a demo about how to send emails in ASP.NET Core in quick & easy steps. We will create an...

ML.NET – Machine Learning with .NET Core – Beginner’s Guide

This article will get you started with the fundamentals of Machine Learning and how to get started with Machine Learning with .NET Core i.e. ML.NET. We will even learn different concepts of Machine learning with a brief overview. Introduction to Machine Learning...

Implement Cookie Authentication in ASP.NET Core – Detailed Guide

This article will get you started with implementing cookie authentication in ASP.NET Core applications. Cookie authentication allows you to have your own login/register screens & custom logic for user-id/password validation without the need to use ASP.NET Core...

ASP.NET Core Identity Roles based Authorization

This article will get you started with what are ASP.NET Core Identity roles and the need for roles, how to enable ASP.NET Core Identity roles in MVC Application, and how to implement role-based authorization. Role-based authorization is for basic authorization where...

Dependency Injection in ASP.NET Core 3.1 – Beginner’s Guide

This article will cover in details dependency injection in ASP.NET Core 3.1. ASP.NET Core is designed from the ground up to support the dependency injection design pattern. Dependency injection in ASP.NET Core provides a technique to create applications that are...

Real-time Web Applications with SignalR in ASP.NET Core 3.1

In this article, we will learn about real-time web & how to build real-time web applications using SignalR in ASP.NET Core. As part of this article, we will work on an application that can send real-time messages/alerts to all connected users or private messages...

Code Profiling using MiniProfiler in ASP.NET Core 3.1

This article will get you started with how to enable miniprofiler in ASP.NET Core to measure the performance of your application. MiniProlifer helps you understand how your application is performing by allowing you to profile any part of code in ASP.NET Core...

Microservices with ASP.NET Core 3.1

Microservices is a type of Architecture in which application is created as multiple small independent serviceable components. This article will cover in detail how to create microservices with ASP.NET Core, Serilog, Swagger UI, Health Checks & Docker containers....

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *