Get Role name in IdentityUserRole 2.0 in ASP.NET

前端 未结 4 1088
甜味超标
甜味超标 2021-01-17 12:43

Before the update of the dll\'s in the Entity Framework i was able to do this

user.Roles.Where(r => r.Role.Name == \"Admin\").FisrtOrDefault(); 


        
相关标签:
4条回答
  • 2021-01-17 13:09

    I've just had almost exactly the same issue and I solved it like this:

    public class UserRole : IdentityUserRole
    {
        public virtual Role Role { get; set; } // add this to see roles
        public virtual User User { get; set; } // add this to see users
    }
    

    Now your original code user.Roles.Where(r => r.Role.Name == "Admin").FirstOrDefault(); will work, which could be handy if you don't have easy access to the RoleManager for any reason.

    0 讨论(0)
  • 2021-01-17 13:10

    Ask the RoleMananger?

    RoleManager.Roles.
    // or
    RoleManager.FindByIdAsync()
    // or 
    RoleManager.FindByNameAsync()
    

    You may want to take some time and learn the new security features in Asp.Net Security and Asp.Net Identity.

    0 讨论(0)
  • 2021-01-17 13:18

    If your aim is to check if a user is in a role you can access it from the IPrincipal.User object in an action

    User.IsInRole("Admin");
    
    0 讨论(0)
  • 2021-01-17 13:22

    Try this

    string id = UserManager.FindByEmail(model.Email).Id;
    IList<string> roleNames=UserManager.GetRoles(id);
    
    0 讨论(0)
提交回复
热议问题