MVC 4路由“查找”区域内的控制器

时间:2013-10-08 19:31:47

标签: c# asp.net-mvc asp.net-mvc-4

我有一个MVC 4 WebSite,有几个区域......我正在使用VS2012创建的所有默认路由......

所以,我可以访问(来自Area1):

Area1/ControllerX/ActionX

我有一些没有区域的控制器,所以我可以访问:

ControllerY/ActionY

一切都很好......但是,如果我尝试在没有Area1的情况下访问ControllerX,那就是:

ControllerX/ActionX

我收到了这个错误:

Exception: The view 'ActionX' or its master was not found or no view engine supports the
searched locations. The following locations were searched: ~/Views/mangavagao/ActionX.cshtml 
~/Views/Shared/ActionX.cshtml 
Controller: ControllerX
Action: ActionX

我当时期待找不到404错误...为什么要捕获该路线?

-

区域路线:

context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { controller = "ControllerX", action = "ActionY", id = UrlParameter.Optional }
);

默认路线:

routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "ControllerY", action = "ActionY", id = UrlParameter.Optional     );

3 个答案:

答案 0 :(得分:5)

在默认的maproute函数中添加namespaces参数。然后将UseNamespaceFallback数据表设置为false

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new string[] { "MvcApplication.Controllers" }
    ).DataTokens["UseNamespaceFallback"] = false;
    当设置多个具有相同名称的控制器时,
  1. namespaces参数设置为优先控制器查找。

  2. 如果在命名空间中找不到匹配项,MVC仍会搜索此命名空间之外的控制器。

  3. UseNamespaceFallback datatoken告诉MVC忽略(2)语句。

  4. 希望这会有所帮助。

答案 1 :(得分:0)

尝试使用命名空间映射区域路径:

context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { controller = "ControllerX", action = "ActionY", id = UrlParameter.Optional },
            new[] { "App.Areas.AreaName.Controllers" }
);

AppAreaName更改为相应的值。

答案 2 :(得分:0)

这与此问题类似:Not including area name in URL results in "The view 'Index' or its master was not found" instead of 404

在您的情况下,名称空间需要添加到默认路由,而不是区域路由。在这种情况下,名称空间不应引用区域控制器。 这样的事情应该有效:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
    null, // object constraints
    new string[] { "Namespace.Application.Controllers" } // namespaces
);