ASP.NET Web API: Using Namespaces to Version Web APIs

ASP.NET Web API: Using Namespaces to Version Web APIs

Rate This
  • Comments 11

In this post, I’ll show how to extend the routing logic in ASP.NET Web API, by creating a custom controller selector. Suppose that you want to version your web API by defining URIs like the following:



You might try to make this work by creating two different “Products” controllers, and placing them in separate namespaces:

namespace MyApp.Controllers.V1
    // Version 1 controller
    public class ProductsController : ApiController {  }

namespace MyApp.Controllers.V2
    // Version 2 controller
    public class ProductsController : ApiController {  }

The problem with this approach is that Web API finds controllers by class name, ignoring the namespace. So there’s no way to make this work using the default routing logic. Fortunately, Web API makes it easy to change the default behavior.

The interface that Web API uses to select a controller is IHttpControllerSelector. You can read about the default implementation here. The important method on this interface is SelectController, which selects a controller for a given HttpRequestMessage.

First, you need to understand a little about the Web API routing process. Routing starts with a route template. When you create a Web API project, it adds a default route template:


The parts in curly brackets are placeholders. Here is a URI that matches this template:

So in this example, the placeholders have these values:

  • controller = products
  • id = 1

The default IHttpControllerSelector uses the value of “controller” to find a controller with a matching name. In this example, “products” would match a controller class named ProductsController. (By convention, you need to add the “Controller” suffix to the class name.)

To make our namespace scenario work, we’ll use a route template like this:


Here is a matching URI:

And here are the placeholder values:

  • namespace = v1
  • controller = products
  • id = 1

Now we can use these values to find a matching controller. First, call GetRouteData to get an IHttpRouteData object from the request:

public HttpControllerDescriptor SelectController(HttpRequestMessage request)
    IHttpRouteData routeData = request.GetRouteData();
    if (routeData == null)
        throw new HttpResponseException(HttpStatusCode.NotFound);

    // ...

Use IHttpRouteData to look up the values of “namespace” and “controller”. The values are stored in a dictionary as object types. Here is a helper method that returns a route value as a type T:

private static T GetRouteVariable(IHttpRouteData routeData, string name)
    object result = null;
    if (routeData.Values.TryGetValue(name, out result))
        return (T)result;
    return default(T);

Use this helper function to get the route values as strings:

string namespaceName = GetRouteVariable<string>(routeData, "namespace");
if (namespaceName == null)
    throw new HttpResponseException(HttpStatusCode.NotFound);

string controllerName = GetRouteVariable<string>(routeData, "controller");
if (controllerName == null)
    throw new HttpResponseException(HttpStatusCode.NotFound);

Now look for a matching controller type. For example, given “namespace” = “v1” and “controller” = “products”, this would match a controller class with the fully qualified name MyApp.Controllers.V1.ProductsController.

To get the list of controller types in the application, use the IHttpControllerTypeResolver interface:

IAssembliesResolver assembliesResolver = 
IHttpControllerTypeResolver controllersResolver = 

ICollection<Type> controllerTypes = 

This code performs reflection on all of the assemblies in the app domain. To avoid doing this on every request, it’s a good idea to cache a dictionary of controller types, and use the dictionary for subsequent look ups.

The last step is to replace the default IHttpControllerSelector with our custom implementation, in the HttpConfiguration.Services collection:

        new NamespaceHttpControllerSelector(config));

You can find the complete sample hosted on

In order to keep the code as simple as possible, the sample has a few limitations:

  • It expects the route to contain a “namespace” variable. Otherwise, it returns an HTTP 404 error. You could modify the sample so that it falls back to the default IHttpControllerSector in this case.
  • The sample always matches the value of “namespace” against the final segment of the namespace (i.e., the inner scope). So “v1” matches “MyApp.Controllers.V1” but not “MyApp.V1.Controllers”. You could change this behavior by modifying the code that constructs the dictionary of controller types. (See the InitializeControllerDictionary method.)

Also, versioning by URI is not the only way to version a web API. See Howard Dierking’s blog post for more thoughts on this topic.

Leave a Comment
  • Please add 5 and 5 and type the answer here:
  • Post
  • Some time ago I created a library for this:

    Note: I'm the author.

  • I think versioning in the URL is fine for short-term migrations, but it's not a good long-term strategy.  It would be much better to see support in the Web API for content-type versioning (as described by Howard).  Changes in the representation of an entity should not affect the URI - that would break the principles of REST.

  • Sebastian, I noticed the similarity. I am using your component by the way.

  • In the sample code hosted on, the code works if the webapi is annoted or using the default [HttpGet].  i have some web api that are annotated with [HttpPost], and it is not working.

    in the request.GetRouteData().Values[0], i have a value of "MS_SubRoutes".   so basically the web api method i am trying to hit, is something like:


    public class Utility : ApiController




    [Authorize(Roles = AUTHORIZED_ROLES)]

    public HttpResponseMessage Cars(Models model)





    how would i handle this situation?

  • Hi Mike,

    how can this be applied to a .NET Backend Mobile service..?

    I tried but I don't know how to handle the "home page" :/

    Thank you :)


  • I have the same problem as Sam, I'd like to use use the NamespaceHttpControllerSelector with RouteAttrobutes. Has anyone managed to get this working?

  • @Tim:

    if you are using attribute routing, you can take a look at the following sample for versioning using constraints:

    FYI regarding customizing controller selector:

  • In this approach if some action in all version of APIs are same, how we can manage these and prevent redundancy in code ( if we copy action in all version, when we find a bug in these action we have to update all of theme in all version)

  • I think my problem with versioning is that all of a sudden you have repetitive code / bloating. Lets say there is a USER class and between 1.0 and 1.1 versions there is one member added to that class. If I need to maintain two versions of controller classes at the same time, I will have to support two User classes in my code. If I can use version 1.0 dll to respond to a version 1.0 request and version 1.1 dll to respond to a version 1.1 request, that would be more appropriate.

  • @Seshu Alluvada & Behrooz

    Pardon me if this is an utterly newbie question. In order to deal with the code redundancy, could you not upon development and release of v2 convert v1 to a parent class? Or is this not possible within the MVC architecture?

  • I tried using your sample code and used the config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config)) code but it seems like the ControllerSelector hasn't been set.

    The full code is

    Should I set the new NamespaceHttpController in the Global.asax instead?

Page 1 of 1 (11 items)