Integrating MVC routes and Web API routes

 

Several folks have been complaining for a while about Action Links not being properly generated when MVC routes are mixed with Service Routes in the same site.

It turns out there is a solution.....don't use ServiceRoute :-) Instead, create a derived route below and use it. [Kudos to Phil Haack and Clemens Vasters for this]

 public class WebApiRoute : ServiceRoute
{
     public AppServiceRoute(string routePrefix, 
       ServiceHostFactoryBase serviceHostFactory, Type serviceType)
     : base(routePrefix, serviceHostFactory, serviceType)
     {
     }
      
     public override VirtualPathData GetVirtualPath(
       RequestContext requestContext, RouteValueDictionary values)
     {
       return null;
     }
}

The link gen functionality uses the GetVirtualPath method to generate links. If you set it to null you are opting web api routes out of link gen and everything should work.

Now to register your routes using this model, don't use MapServiceRoute.

Instead, in add to your route table manually this way:

 var config = new HttpHostConfiguration() ///create your config object
var factory = new HttpConfigurableServiceHostFactory(config);

routes.Add(new WebApiRoute("Foo", factory, typeof(Foo)));

It's a little bit more code, but not too much and hey, it fixes the problem. This will be fixed in the next drop, which YES, we are working on.