如何为其他用户登录后获取UserRoles

时间:2014-03-11 06:52:36

标签: c# entity-framework asp.net-mvc-5 roles asp.net-identity

在帐户控制器的索引操作中,我希望能够允许用户查看状态相同或较低的用户,但我没有得到我想要的结果。一种方式只返回登录用户,另一种方式不返回任何内容。用户只能拥有一个角色。到目前为止,我有这个,

var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
IList<string> roles;

foreach (var item in pUsers)
{
   userDetails = new listUsersViewModel();
   userDetails.id = item.id;
   userDetails.userName = cEncrypt.decryptUserName(item.userName.Substring(2));

   //***this only returns the role of Logged in User
   roles = um.GetRoles(item.id);

   //***this doesn't return any results
   string[] role = Roles.GetRolesForUser(item.userName);

   //make sure the logged in user has appropriate permissions to view list of users.
   if ((User.IsInRole("Admin") && ((roles[0] == "Admin") || (roles[0] == "Staff") || (roles[0] == "User")))
      || (User.IsInRole("Staff") && ((roles[0] == "Staff") || (roles[0] == "User")))
      || (User.IsInRole("User") && User.Identity.GetUserId() == userDetails.id)
      )
      { userList.Add(userDetails); }
}

项目根目录中的web.config看起来像这样......

<system.web>
  <roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
    <providers>
      <clear/>
      <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="DefaultConnection" applicationName="myDatabaseName" />
    </providers>
  </roleManager>
</system.web>

感谢您的帮助。

0 个答案:

没有答案