Get Role name in IdentityUserRole 2.0 in ASP.NET

情到浓时终转凉″ 提交于 2019-12-19 12:54:23

问题


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


回答1:


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.




回答2:


Try this

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



回答3:


If your aim is to check if a user is in a role you can access it from the IPrincipal.User object in an action

User.IsInRole("Admin");



回答4:


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.



来源:https://stackoverflow.com/questions/30670817/get-role-name-in-identityuserrole-2-0-in-asp-net

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