在后面的代码中获取用户角色

时间:2014-07-29 06:16:02

标签: c# asp.net code-behind asp.net-identity

如何在代码中获取用户角色?例如

HttpContext.Current.User.Identity.GetUserId(); 

会给我UserId。但是我怎么能得到这个角色呢?

由于

2 个答案:

答案 0 :(得分:1)

如果要获取用户角色列表(返回角色作为列表):

C#:

string strUserId = User.Identity.GetUserId();
UserManager userManager = new UserManager();
foreach (object roleName in userManager.GetRoles(strUserId)) {
    roleName = roleName;
    lblMsg.Text += roleName;
}


VB:

Dim strUserId As String = User.Identity.GetUserId
Dim userManager As New UserManager
For Each roleName In userManager.GetRoles(strUserId)
    lblMsg.Text += roleName
Next



如果要检查用户是否处于特定角色(返回为布尔值):

C#:

string strUserId = User.Identity.GetUserId();
UserManager userManager = new UserManager();
lblMsg.Text = userManager.IsInRole(strUserId, "Admin");


VB:

Dim strUserId As String = User.Identity.GetUserId
Dim userManager As New UserManager
lblMsg.Text = userManager.IsInRole(strUserId, "Admin")

答案 1 :(得分:0)

您可以使用Roles.GetRolesForUser方法获取当前登录用户的角色。

<强> MSDN链路

Roles.GetRolesForUser Method

示例:(取自msdn)

string[] rolesArray;

public void Page_Load()
{
  if (!IsPostBack)
  {
    // Bind roles to GridView.

    try
    {
      rolesArray = Roles.GetRolesForUser();
    }
    catch (HttpException e)
    {
      Msg.Text = "There is no current logged on user.";
      return;
    }
  }
}