Asp.net-Mvc

MVC 4 擷取所有從未到達的路線

  • May 20, 2014

當嘗試在 MVC 4 中創建一個 catch all 路由時(我已經找到了幾個範例,並且基於我的程式碼),它返回一個 404 錯誤。我在 IIS 7.5 上執行它。這似乎是一個直接的解決方案,所以我錯過了什麼?

請注意,如果我將“CatchAll”路線移動到“預設”路線上方,它會起作用。但是當然,其他控制器都沒有到達。

這是程式碼:

路線配置:

       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();
   }

}

由於創建包羅萬象的路線的最終目標是能夠處理動態網址,而我無法找到上述原始問題的直接答案,因此我從不同的角度進行了研究。在這樣做時,我遇到了這篇博文:沒有路由匹配時的自定義 404

此解決方案允許處理給定 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://stackoverflow.com/questions/16527740