There are occasions you would like or need to add versioning to your API in order to specify availability or non-availability of functionality.

There are a few options available to such as Query String, Url based as well as Http header.

For my purposes I am going to talk about the Url based approach, as I have implemented this option in my MyReverie repo due to a matter of preference of being cleaner and more explicit.

First things first we will need to go ahead and install the Nuget package:

  • Microsoft.AspNetCore.Mvc.Versioning

Within the Startup class ConfigureServices method add the below:

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

 

The above three properties are particularly useful in that they allow default versions to be set if none are explicitly set as well as providing header information on versioning that are supported.

ReportApiVersions: we are requesting the header to respond with supported API versions

AssumeDefaultVersionWhenUnspecified: set the default version if none are explicitly requested

DefaultApiVersion: Set the default version to 1.0 if default is used

To better illustrate the first property above see below. I used Postman to see the response header with supported versions listed, which I highlighted

Versioning_thumb7

Now all I have to do is simply add and update the controller attribute in my case

At the moment as I am still on version 1, I will add the attribute

 [ApiVersion("1.0")] 

and update the route attribute like so:

 [Route("api/{v:apiVersion}/[controller]")] 

So the result of the Controller class(GoalsController in my case) attributes should look like the below

Versioning_thumb1

Now let’s test our F5 and browse to our API endpoint with suffix : /api/1.0/goals, in my case below.

Versioning_thumb3

That’s it my API is now versioned v1.0