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

后端 未结 8 807
日久生厌
日久生厌 2020-12-04 17:47

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

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 18:33

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

    private static bool IsInAnyRole(this IPrincipal user, List roles)
    {
        var userRoles = Roles.GetRolesForUser(user.Identity.Name);
    
        return userRoles.Any(u => roles.Contains(u));
    }
    

    For usage, do:

    var roles = new List { "Admin", "Author", "Super" };
    
    if (user.IsInAnyRole(roles))
    {
        //do something
    }
    

    Or without the extension method:

    var roles = new List { "Admin", "Author", "Super" };
    var userRoles = Roles.GetRolesForUser(User.Identity.Name);
    
    if (userRoles.Any(u => roles.Contains(u))
    {
        //do something
    }
    

提交回复
热议问题