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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – MVC 4捕获所有路由从未到达前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当尝试在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.f2er.com/aspnet/248949.html

猜你在找的asp.Net相关文章