Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
Sadik Ali Avatar asked Aug 14 '17 12:08

Sadik Ali


People also ask

How do you get user role in identity?

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.


1 Answers

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;
}
like image 70
Zahir Firasta Avatar answered Sep 22 '22 07:09

Zahir Firasta