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

后端 未结 8 809
日久生厌
日久生厌 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:48

    Please, use this simple way :

    @using Microsoft.AspNet.Identity
    
    @if (Request.IsAuthenticated)
    {
        if (User.IsInRole("Administrator") || User.IsInRole("Moderator"))
        {
            ... Your code here
        }
    }
    
    0 讨论(0)
  • 2020-12-04 18:52

    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
    }
    
    0 讨论(0)
提交回复
热议问题