当尝试在MVC 4中创建捕获所有路由时(我发现了几个示例,基于我的代码),它返回404错误.我在IIS 7.5上运行它.这似乎是一个直接的解决方案,所以我错过了什么?
需要注意的是,如果我将“CatchAll”路线移动到“默认”路线上方,则可以使用.但是当然没有其他控制器到达.
这是代码:
Route.Config:
routes.MapRoute( name: "Default",url: "{controller}/{action}/{id}",defaults: new { controller = "Home",action = "Index",id = UrlParameter.Optional } ); routes.MapRoute( "CatchAll","{*dynamicRoute}",new { controller = "CatchAll",action = "ChoosePage" } );
控制器:
public class CatchAllController : Controller { public ActionResult ChoosePage(string dynamicRoute) { ViewBag.Path = dynamicRoute; return View(); } }
解决方法
由于创建捕获路线的最终目标是能够处理动态网址,而我无法找到上述原始问题的直接答案,因此我从不同的角度研究了我的研究.在这样做时,我遇到了这篇博文:
Custom 404 when no route matches
该解决方案允许处理给定URL内的多个部分
(即www.mysite.com/this/is/a/dynamic/route)
public override IController CreateController(System.Web.Routing.RequestContext requestContext,string controllerName) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } if (String.IsNullOrEmpty(controllerName)) { throw new ArgumentException("MissingControllerName"); } var controllerType = GetControllerType(requestContext,controllerName); // This is where a 404 is normally returned // Replaced with route to catchall controller if (controllerType == null) { // Build the dynamic route variable with all segments var dynamicRoute = string.Join("/",requestContext.RouteData.Values.Values); // Route to the Catchall controller controllerName = "CatchAll"; controllerType = GetControllerType(requestContext,controllerName); requestContext.RouteData.Values["Controller"] = controllerName; requestContext.RouteData.Values["action"] = "ChoosePage"; requestContext.RouteData.Values["dynamicRoute"] = dynamicRoute; } IController controller = GetControllerInstance(requestContext,controllerType); return controller; }