8

When attempting to create a catch all route in MVC 4 (something I've found several examples of, and based my code on) it returns a 404 error. I'm running this on IIS 7.5. This seems like a straight forward solution, so what am I missing?

One note, if I move the "CatchAll" route above the "Default" route it works. But of course then none of the other controllers are ever reached.

Here is the code:

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

Controller:

public class CatchAllController : Controller
{

    public ActionResult ChoosePage(string dynamicRoute)
    {
        ViewBag.Path = dynamicRoute;
        return View();
    }

}
4

3 に答える 3

9

キャッチオール ルートを作成する最終的な目標は動的 URL を処理できるようにすることであり、上記の元の問題に対する直接的な答えを見つけることができなかったため、別の観点から研究に取り組みました。そうすることで、私はこのブログ投稿に出くわしました:ルートが一致しない場合のカスタム 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;
 }
于 2013-05-14T13:10:41.663 に答える
0

ルートでオプションの文字列 dynamicRoute パラメータを定義してみてください。

 routes.MapRoute( 
      "CatchAll", 
      "{*dynamicRoute}", 
      new { controller = "CatchAll", action = "ChoosePage", dynamicRoute = UrlParameter.Optional } );
于 2013-05-13T17:59:15.913 に答える