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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With