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

£可爱£侵袭症+ 提交于 2019-12-05 03:31:35

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;
}
Fábio Rodrigues Fonseca

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;
        }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!