16

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?

SadikAli
  • 594
  • 1
  • 4
  • 21

2 Answers2

28

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;
}
Zahir Firasta
  • 533
  • 6
  • 12
4

If you has a list of users you has to do this:

var usuarioManager = Request.GetOwinContext().GetUserManager<UserManager<Usuario>>();
var roleManager = Request.GetOwinContext().Get<RoleManager<IdentityRole>>();

var roles = roleManager.Roles.ToList();

var usuarios = usuarioManager.Users.Include(x => x.Roles).ToList();

usuarios.ForEach((x) =>
{
    if (x.Roles.Any())
    {
        var roleDb = roles.FirstOrDefault(r => r.Id == x.Roles.FirstOrDefault().RoleId);
        if (roleDb != null)
            x.RoleName = roleDb.Name;
        }
});
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228