【问题标题】:In MVC3 how to restrict access to an Area with a role-based authorization?在 MVC3 中,如何通过基于角色的授权来限制对区域的访问?
【发布时间】:2012-11-17 10:29:17
【问题描述】:

在 MVC3 中,我们可以使用 [Authorize] 属性限制对控制器的访问,指定用户必须具有管理员角色才能访问类中的任何控制器操作,如下例所示...

[Authorize(Roles = "Administrator")]
public class MyDefaultController : Controller
{
    // Controller code here
}

但是如何在 MVC3 中限制对整个区域的访问,而不为区域内的每个控制器类指定 [Authorize] 属性?

【问题讨论】:

    标签: asp.net-mvc-3 controller authorization asp.net-mvc-areas role-base-authorization


    【解决方案1】:

    您可以使用 RouteConstraints 来执行此操作:

    这样写一个类:

           public class AreaRouteConstraint : IRouteConstraint
            {
                public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
                {
                    return  Validate(values["area"];
    
    
                }
           }
    

    实现Validate 方法取决于您。

    并像这样使用它:

     routes.MapRoute(
    name: "yourRouteName",
    url: "Url",
    defaults: new { controller = "controller", action = "action" , area="area" },
    constraints: new AreaRouteConstraint ()
    );
    

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 2013-02-13
      • 1970-01-01
      • 2020-04-09
      • 2020-05-15
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多