简体   繁体   中英

Get Role name in IdentityUserRole 2.0 in ASP.NET

Before the update of the dll's in the Entity Framework i was able to do this

user.Roles.Where(r => r.Role.Name == "Admin").FisrtOrDefault(); 

Now, i can only do r.RoleId, and i can't find a way to retreive the name of thar Role Id. I'm using this in my controllers and in my AuthorizeAttribute class.

Can someone help me here?

Regards

Ask the RoleMananger ?

RoleManager.Roles.
// or
RoleManager.FindByIdAsync()
// or 
RoleManager.FindByNameAsync()

You may want to take some time and learn the new security features in Asp.Net Security and Asp.Net Identity .

Try this

string id = UserManager.FindByEmail(model.Email).Id;
IList<string> roleNames=UserManager.GetRoles(id);

如果您的目的是检查用户是否在角色中,您可以从动作中的IPrincipal.User对象访问它

User.IsInRole("Admin");

I've just had almost exactly the same issue and I solved it like this:

public class UserRole : IdentityUserRole
{
    public virtual Role Role { get; set; } // add this to see roles
    public virtual User User { get; set; } // add this to see users
}

Now your original code user.Roles.Where(r => r.Role.Name == "Admin").FirstOrDefault(); will work, which could be handy if you don't have easy access to the RoleManager for any reason.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM