开发者

If User.IsInRole with string array?

Im trying to build a custom validation where I check if the role contains a user. And I'm having problems with string array, what is best way to check if it contains a specific value?

    public string[] AuthRol开发者_StackOverflow中文版es { 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");
        }

How should I modify the check for User.IsInRole so it handles the array?


How about:

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

Edit: (Assuming that being member of any of the roles is enough to be authorized.)


If you want the user to have all the roles in the AuthRoles at the same time, you should:

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

If just being a member of at least one of the required roles is enough, use Any:

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


You can do it with a simple linq expression:

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


You need to check each string

bool isAuthorized = false;

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜