如何在Asp.Net Identity中获取用户的角色名称 [英] How to get role name for user in Asp.Net Identity
问题描述
我试图弄清楚如何在身份框架中找到用户角色名称.
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.
所以,我尝试使用
public string GetUserRole(string EmailID, string Password)
{
var user = await _userManager.FindAsync(EmailID, Password);
var roleid= user.Roles.FirstOrDefault().RoleId;
}
但是我得到的只是RoleId,而不是RoleName.
But what I get is just RoleId and not RoleName.
有人可以帮我找到用户的RoleName吗?
Can anyone help me to find the RoleName for the user?
推荐答案
在您的代码中,user
对象表示AspNetUsers
表,该表具有导航属性Roles
,该导航属性表示AspNetUserInRoles
表而不是AspNetRoles
表格.
因此,当您尝试浏览
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()
它为您提供了AspNetUserInRoles
,其中存储了UserId和RoleId.
it gives you the AspNetUserInRoles
which stores UserId and RoleId.
您可以尝试使用UserManger
的GetRoles
方法,该方法将返回给您分配了用户角色的List<string>
.但是正如您提到的那样,它只是一个角色,因此您可以从GetRoles
方法的结果中获取第一个值.
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;
}
这篇关于如何在Asp.Net Identity中获取用户的角色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!