How can I check if a user is in any one of a few d

2019-01-13 07:45发布

问题:

I understand that a good way to check if an user is in a role is:

if (User.IsInRole("Admin"))
{

}

However How can I check if my user is in one of the "Author", "Admin" or "Super" roles? Is there a way to do this without coding "User.IsInRole" for each of the roles?

回答1:

EDIT: Without coding each role, do it a LINQ extension method, like so:

private static bool IsInAnyRole(this IPrincipal user, List<string> roles)
{
    var userRoles = Roles.GetRolesForUser(user.Identity.Name);

    return userRoles.Any(u => roles.Contains(u));
}

For usage, do:

var roles = new List<string> { "Admin", "Author", "Super" };

if (user.IsInAnyRole(roles))
{
    //do something
}

Or without the extension method:

var roles = new List<string> { "Admin", "Author", "Super" };
var userRoles = Roles.GetRolesForUser(User.Identity.Name);

if (userRoles.Any(u => roles.Contains(u))
{
    //do something
}


回答2:

There's no built-in way to check if a user is in multiple roles, but it's pretty trivial to create a nice extension method to handle it for you:

public static bool IsInAnyRole(this IPrincipal principal, params string[] roles)
{
    return roles.Any(principal.IsInRole);
}

Usage then is:

if (User.IsInAnyRole("Admin", "Author", "SuperUser"))
{

}


回答3:

I wanted to elaborate a little on mattytommo's answer, here is what I use:

Extension Method:

public static bool IsInAnyRole(this IPrincipal user, string[] roles)
        {
            //Check if authenticated first (optional)
            if (!user.Identity.IsAuthenticated) return false;
            var userRoles = Roles.GetRolesForUser(user.Identity.Name);
            return userRoles.Any(roles.Contains);
        }

Constants:

public static class Role
{
    public const string Administrator = "Administrator";
    public const string Moderator = "Moderator";
}

Usage:

if (User.IsInAnyRole(new [] {Role.Administrator,Role.Moderator}))
{
    //Do stuff
}


回答4:

You can also use

if(Roles.GetRolesForUser(model.UserName).Contains("Admin")){
}


回答5:

I used the below code. In my case, I had a semi colon de-limited string as the parameter which is read from web.config. You may change the below code easily if you are passing a List.

public class ActiveDirectoryGroup
{
    public static bool IsInAnyRole(string adRoles)
    {
        return adRoles.Split(Convert.ToChar(";")).Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
        //If list is passed use below
        //return listParameter.Any(role => !string.IsNullOrEmpty(role.Trim()) && HttpContext.Current.User.IsInRole(role.Trim()));
    }
}

In web.config:

<appSettings>
  <add key="ADGroup" value="Domain\Admin;Domain\Supervisor;Domain\Manager;" />
</appSettings>

I used it like below in my page load:

if (ActiveDirectoryGroup.IsInAnyRole(ConfigurationManager.AppSettings["ADGroup"]))
{
  //do something
}


回答6:

In my case i just have one role per user. So i did it like this:

if (User.Roles.FirstOrDefault().RoleId == "7b433246-5881-4ace-bbaa-e5514191171c") {
    //Do something
}


回答7:

Please, use this simple way :

@using Microsoft.AspNet.Identity

@if (Request.IsAuthenticated)
{
    if (User.IsInRole("Administrator") || User.IsInRole("Moderator"))
    {
        ... Your code here
    }
}