加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC 4捕获所有路由从未到达

发布时间:2020-12-15 22:17:24 所属栏目:asp.Net 来源:网络整理
导读:当尝试在MVC 4中创建捕获所有路由时(我发现了几个示例,基于我的代码),它返回404错误.我在IIS 7.5上运行它.这似乎是一个直接的解决方案,所以我错过了什么? 需要注意的是,如果我将“CatchAll”路线移动到“默认”路线上方,则可以使用.但是当然没有其他控制器
当尝试在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;
 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读