Search code examples
asp.netasp.net-identity-2

How to get role name for user in Asp.Net Identity


I am trying to figure out how to find user role name in identity framework.

I have such configuration that there will be only one role assigned to a user.

So, I tried using

public string GetUserRole(string EmailID, string Password)
{
    var user = await _userManager.FindAsync(EmailID, Password);
    var roleid= user.Roles.FirstOrDefault().RoleId;
}

But what I get is just RoleId and not RoleName.

Can anyone help me to find the RoleName for the user?


Solution

  • In your code, user object represents the AspNetUsers table which has a navigation property Roles which represents the AspNetUserInRoles table and not the AspNetRoles table. So when you try to navigate through

    user.Roles.FirstOrDefault()
    

    it gives you the AspNetUserInRoles which stores UserId and RoleId.

    Instead you could try UserManger's GetRoles method which will return you List<string> of roles user is assigned. But as you mentioned it will be only one role hence you can take first value from the result of GetRoles method.

    Your function should be similar to one given below:

    public async string GetUserRole(string EmailID, string Password)
    {
        var user = await _userManager.FindAsync(EmailID, Password);
        string rolename = await _userManager.GetRoles(user.Id).FirstOrDefault();
        return rolename;
    }