Search code examples
c#.netasp.net-mvcasp.net-mvc-3asp.net-mvc-4

How can I check if a user is in any one of a few different roles with MVC4 Simple membership?


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?


Solution

  • 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
    }