Wednesday, October 22, 2014

Multiple RoutePrefix

In MVC5 Microsoft has added routing using C# attributes. It is hard to overestimate this feature: finally you don't need to switch between your controllers and RoutesConfig.cs to find out where all your endpoints go.
To make it even sweeter they added RoutePrefix attribute, which sets one prefix to multiple actions. Though you can set multiple Route attributes for each action, you cannot set multiple RoutePrefix. And this is very frustrating when you need to have multiple paths to the same action. Luckily, the framework is very customizable (many thanks for that), so we can easily fix this drawback.

Introducing RouteMPrefix attribute, which supports multiple instances and your code looks like:
[RouteMPrefix("v1/values")]
[RouteMPrefix("v2/values")]
public class ValuesController : ApiController
{
  [Route("list")]
  [Route("get")]
  public IEnumerable Get()
  {
    return new[] { "value1", "value2" };
  }
}

As a result all the following routes will be created:
  • /v1/values/list
  • /v1/values/get
  • /v2/values/list
  • /v2/values/get

And to make it all work you need:
1. Add two files MultiPrefixRouteProvider.cs and RouteMPrefixAttribute.cs from this GitHub repository

2. Use MultiPrefixRouteProvider when initializing attribute routing:
config.MapHttpAttributeRoutes (new MultiPrefixRouteProvider());


This is it. Happy coding.