ASP.NET MVC3区域控制器可从全局路由访问?

Dua*_*ane 5 asp.net-mvc asp.net-mvc-routing asp.net-mvc-areas

也许我不能正确理解MVC区域是如何工作的,但这让我有些困惑.

  1. 使用在MVC3项目上的Visual Studio中右键单击"添加区域"添加名为"MyArea"的区域
  2. 为MyArea创建一个控制器:在MyArea区域中具有匹配视图的"AnArea".
  3. 将"controller ="AnArea"添加到MyAreaAreaRegistration.RegisterArea方法中的context.MapRoute的defaults参数中.

所以此时如果你启动应用程序并导航到/ MyArea /它应该加载AnArea控制器及其匹配视图.如果导航到/ MyArea/AnArea,它将显示相同的结果.

但是,如果您导航到/ AnArea /,仍然会找到控制器并显示以下错误消息:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/anarea/Index.aspx
~/Views/anarea/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/anarea/Index.cshtml
~/Views/anarea/Index.vbhtml
~/Views/Shared/Index.cshtml
~/Views/Shared/Index.vbhtml
Run Code Online (Sandbox Code Playgroud)

这是正确的行为吗?我原以为一个区域的控制器只能通过它自己的区域访问而不是全局访问.

cou*_*ben 6

每当我创建一个包含区域的项目时,我都会Default按如下方式更改路线:

    routes.MapRoute( 
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // defaults
        null,  // constraints
        new string[] { "MyApplication.Controllers" } // namespaces
    );
Run Code Online (Sandbox Code Playgroud)

最后一个参数限制了MyApplication.Controllers命名空间中控制器的默认路由.这可确保默认路由仅限于任何区域之外的操作.

UPDATE

在深入研究代码之后,我发现了问题出现的地方,并找到了解决方案.将您的默认路由更改为以下内容:

routes.Add(
    "Default", 
    new Route("{controller}/{action}/{id}",
        new RouteValueDictionary(
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        ),
        null,
        new RouteValueDictionary(
            new {
                Namespaces = new string[] { "MyApplication.Controllers" },
                UseNamespaceFallback = false 
            }
        ),
        new MvcRouteHandler()
    )
);
Run Code Online (Sandbox Code Playgroud)

关键是添加UseNamespaceFallback令牌.这将阻止Default路由查看任何其他名称空间.

这是意外的行为,这是一个我不知道哪个影响我正在处理的项目的问题.我将在aspnet.codeplex.com上将其列为问题.我不会称这是一个错误,但这种行为肯定会破坏MVC路由的召集.