1

我真的不知道应该用什么标题来描述我的问题。为了简化我的问题。这是我的测试。我从头开始创建一个 mvc3 站点。然后我添加名为“admin”的区域。在 admin 内部,我有一个名为“Search”的控制器,并装饰了“Authorize”属性。然后我更改了我的 Global.ascx.cs 路由设置以附加我的控制器命名空间。现在我开始我的测试。

问题 1

当我访问http://localhost:xxx/Search页面时,它会将我重定向回 /Account/Logon 页面,这让我首先感到困惑,为什么它会将我重定向到登录页面?据我了解,它根本不应该到达管理员搜索控制器。如果我删除了 Authorize 属性,它会显示黄色屏幕,说找不到我预期的视图。

问题2

如果我添加带有角色的授权属性,例如(Roles="Admin"),那么我会再次尝试访问搜索页面,无论登录成功与否,我总是会重定向回登录页面。为什么它不给我黄屏,因为我试图在主站点而不是管理区域请求搜索控制器索引视图。很困惑。

我是 MVC 开发的新手,有人可以为我的问题提供解决方案吗?

谢谢

全球.ascx.cs

        public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },                      
            new string[]{"TestAreaRouting.Controllers"}
          );

        }
4

1 回答 1

1

You could constrain the default controller factory to look only inside the specified namespace for controllers in the RegisterRoutes method of Global.asax by setting the UseNamespaceFallback data token to false:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        new string[] { "TestAreaRouting.Controllers" }
    ).DataTokens["UseNamespaceFallback"] = false;
}

If you don't do this when you request /search the admin area route doesn't match because the url doesn't start with the Admin prefix.

So it is the default route that matches. The default controller factory starts scanning the assembly for a class called SearchController that derives from Controller and since it finds one it instantiates it and uses it to serve the request. Obviously it doesn't find a corresponding Index view because it looks in ~/Views/Search/Index.cshtml which obviously doesn't exist. The actual view is located in the area.

Now that we have constrained the controllers to their respective locations you could decorate them with the Authorize attribute and it should behave consistently.

于 2011-12-06T13:07:57.350 回答