asp.net-mvc-2iroutehandler

Custom IRouteHandler route screws up MVC link building


I have a custom routehandler in ASP.NET MVC2 to catch all url's at a prefixed path like this:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add(new Route("@api/{*all}", new ApiHandler()));
routes.MapRoute(
  "Default", // Route name
  "{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Routing works fine, but if i use Html.Actionlink or return ReturnToAction() from a controller, the uri built creates a broken uri like this:

/@api?action=Add&controller=Home

instead of

/Home/Add

How can i influence the uri building logic to consider the Default route pattern?


Solution

  • I've come up with a hack to stop the described behavior. While this "solves" the problem, it's really kind of nasty and I'd prefer a cleaner way to exclude a route from the virtual path building logic

    routes.Add(
      new Route("@api/{*all}",
      // A random and unlikely controller name as the default
      new RouteValueDictionary() { { "controller", "qwewqewqeqweq" } },
      // and a constraint requiring any controller to be that random, default value
      new RouteValueDictionary() { { "controller", "qwewqewqeqweq" } }, 
      new ApiHandler()
    );
    

    This means that the route would only be chosen for Virtual Path building if the controller in question was "qwewqewqeqweq", which hopefully is unlikely. I said it was nasty.