Versioning Web API Controllers in .Net Core

Peter Lazzarino
Go Ahead Tours — Tech Blog
2 min readOct 5, 2016

Background

Our team is currently in the process of migrating our C# code to micro services. One of our goals was to create endpoints that could be versioned for backward compatibility with our clients (web, mobile app, etc). In past versions of .Net web API it was as easy as creating your own IHttpControllerSelector and replacing the default selector with yours.

Microsoft goes in depth on this topic in an MSDN blog post — asp net web api using namespaces to version web apis

In .Net Core IHttpControllerSelector is no longer available however it’s still just as easy to set up versioning. Instead of replacing internal services with your own implementation you can now register IApplicationModelConventions. This interface allows for some deep customizations of the framework. I’m not going to go too deeply into what it does here but there are some great resources available including this post Strongly Typed routing for MVC 6

Creating our Routing Convention

First we create our class that implements the IApplicationModelConvention interface provided in the Microsoft.AspNetCore.Mvc package.

public class NameSpaceVersionRoutingConvention : IApplicationModelConvention

inside of our class we implement the Apply method defined by the interface with an ApplicationModel parameter.

public void Apply(ApplicationModel application)

the application model parameter has a property Controllers that contains the controllers in our Web Api application.

In the full class shown below you can see we iterate through the controllers, ignoring those that already have a route attribute defined and those that do not have a version number in their namespace.

Let’s use the following folder structure as an example to go off of

Sample folder structure

We find the version number by identifying a namespace segment that has a v followed by any number of integers. The controller above will have the following route defined.

/api/v1/BaseConfiguration/

Actions inside that controller with routes defined can follow this convention so each controller in any number of version folders can have their action routes also be defined per version.

The full code for the class that creates the routes is listed below.

You can find this project on github and nuget at the following links

https://www.nuget.org/packages/versionrouting/

Sample folder structure with version in URL

--

--