MVC路由在根处拾取区域控制器

fyj*_*ham 4 .net c# asp.net-mvc-4

我在区域内的控制器遇到困难时,区域内的路由会回应请求.所以我有这样的设置(额外的东西削减):

/Areas/Security/Controllers/MembersController.cs
/Areas/Security/SecurityAreaRegistration.cs
/Controllers/HomeController.cs
Run Code Online (Sandbox Code Playgroud)

我有我的安全区域定义:

namespace MyApp.Web.Areas.Security
{
    public class SecurityAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Security";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Security_default",
                "Security/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的全球路由规则:

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*robotstxt}", new { robotstxt = @"(.*/)?robots.txt(/.*)?" });
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new string[] { "MyApp.Web.Controllers" }
        );
Run Code Online (Sandbox Code Playgroud)

在我的全局asax中,我做了很多事情,但相关的部分是我打电话AreaRegistration.RegisterAllAreas();然后我调用上面做的路由功能.

但我的问题是"/ Members /"的请求使用我的"默认"路由命中我的会员控制器...即使控制器不在我指定的命名空间中.然后,当它试图运行时,它找不到它的视图,因为它们在区域中定义,并且它试图在整个视图文件夹中找到它们.我尝试制作路由命名空间"Weird.Namespace.With.No.Content",它仍然命中成员控制器 - 我找不到任何方法使它不使用该控制器.如何让它不回答不在其区域内的请求?

fyj*_*ham 7

通过将路线更改为:找到解决方案:

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new string[] { "MyApp.Web.Controllers" }
    ).DataTokens["UseNamespaceFallback"] = false;
Run Code Online (Sandbox Code Playgroud)

出于某种原因,无论如何,它似乎总能找到我的控制器,无论它们在哪里,完全忽略我的命名空间 - 甚至是来自其他引用的程序集.通过DefaultControllerFactory它的ILSpy 看起来GetControllerType最终会回到绝对搜索每个控制器,如果它没有找到您要求的名称空间中的控制器...

这个标志似乎是在我在特定区域制作的路由上自动设置的,而不是我在全局制作的路径上设置的.当我把它放在全球的时候,他们开始表现我原先的预期.我不知道你为什么要打开这个......