当尝试在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; }
原文地址:https://www.jb51.cc/aspnet/248949.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。