如果User.IsInRole有字符串数组?

时间:2010-02-01 09:30:09

标签: c# asp.net-mvc forms-authentication

我正在尝试构建自定义验证,我检查角色是否包含用户。我遇到字符串数组的问题,检查它是否包含特定值的最佳方法是什么?

    public string[] AuthRoles { get; set; }


    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {

        if (AuthRoles.Length > 0)
        {

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {

               RedirectToRoute(filterContext,
               new
               {
                   controller = "AdminLogin",
                   action = "AdminLogin"
               });

            }
            else
            {
                bool isAuthorized = filterContext.HttpContext.User.IsInRole(this.AuthRoles.??);

                if (!isAuthorized)
                    throw new UnauthorizedAccessException("You are not authorized to view this page");
            }
        }
        else
        {
            throw new InvalidOperationException("No Role Specified");
        }

我应该如何修改User.IsInRole的检查以便它处理数组?

4 个答案:

答案 0 :(得分:12)

怎么样:

bool isAuthorized = 
    this.AuthRoles.Any(r => filterContext.HttpContext.User.IsInRole(r));

编辑:(假设成为任何角色的成员足以获得授权。)

答案 1 :(得分:8)

如果您希望用户同时拥有AuthRoles中的所有角色,您应该:

bool isAuthorized =
         Array.TrueForAll(AuthRoles, filterContext.HttpContext.User.IsInRole);

如果只是成为至少一个所需角色的成员就足够了,请使用Any

bool isAuthorized = AuthRoles.Any(filterContext.HttpContext.User.IsInRole);

答案 2 :(得分:2)

您可以使用简单的linq表达式执行此操作:

bool isAuthorized = AuthRoles.All(filterContext.HttpContext.User.IsInRole);

答案 3 :(得分:1)

您需要检查每个字符串

bool isAuthorized = false;

foreach(string role in AuthRoles)
{
  if(filterContext.HttpContext.User.IsInRole(role))
    isAuthorized = true;
}