Custom IRouteHandler route screws up MVC link building

醉酒当歌 提交于 2019-12-08 03:49:08

问题


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?


回答1:


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.




回答2:


You could specify the name of the route using the RouteLink helper:

<%: Html.RouteLink("link text", "Default", 
    new { action = "add", controller = "home" }) %>


来源:https://stackoverflow.com/questions/4351415/custom-iroutehandler-route-screws-up-mvc-link-building

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!