ASP.NET Identity如何获取所有用户和所有角色

16

我在VS 2013中创建了一个新项目。我正在使用身份验证系统,但是我不知道如何获取应用程序中所有用户和所有角色的列表。我正在尝试创建一些管理页面,以便我可以添加新角色,将角色添加到用户中,查看谁已登录或锁定。

有人知道如何做到这一点吗?

4个回答

27
在ASP.NET Identity 1.0中,您需要直接从DbContext中获取此信息...
var context = new ApplicationDbContext();
var allUsers = context.Users.ToList();
var allRoles = context.Roles.ToList();
在 ASP.NET Identity 2.0(目前处于 Alpha 版本),此功能可在 UserManagerRoleManager 上使用...
userManager.Users.ToList();
roleManager.Roles.ToList();
在两个版本中,您将与RoleManagerUserManager进行交互,以创建角色并将角色分配给用户。

2
谢谢你,伙计。这个很有效。期待2.0版本会更加容易些。 - Andy Xufuris
有没有办法过滤用户并获取已登录的用户?我似乎在IdentityUser类中找不到这样的字段。 - SoManyGoblins
4
这种功能无法直接使用。可能是因为这很难实现,而“已登录”的定义因应用程序而异。例如,用户是否在注销之前一直处于登录状态?如果他们使用多个浏览器或设备,并且在其中一个上退出了登录怎么办?也许在某些情况下,“已登录”意味着用户在过去的x分钟内一直活跃。您希望它在您的应用程序中如何工作?也许这是讨论的良好起点。 - Anthony Chu

4

在Anthony Chu所说的基础上,在Identity 2.x中,您可以使用自定义的助手方法获取角色:

public static IEnumerable<IdentityRole> GetAllRoles()
{
    var context = new ApplicationDbContext();
    var roleStore = new RoleStore<IdentityRole>(context);
    var roleMgr = new RoleManager<IdentityRole>(roleStore);
    return roleMgr.Roles.ToList();
}

1
在Anthony Chu和Alex的基础上构建。
创建两个帮助类...
    public class UserManager : UserManager<ApplicationUser>
      {
        public UserManager() 
            : base(new UserStore<ApplicationUser>(new ApplicationDbContext()))
            { }
       }

     public class RoleManager : RoleManager<IdentityRole>
     {
        public RoleManager()
            : base(new RoleStore<IdentityRole>(new ApplicationDbContext()))
        { }
      }

获取角色和用户的两种方法。

   public static IEnumerable<IdentityRole> GetAllRoles()
    {
        RoleManager roleMgr = new RoleManager();
        return roleMgr.Roles.ToList();
    }

    public static IEnumerable<IdentityUser> GetAllUsers()
    {
        UserManager userMgr = new UserManager();
        return userMgr.Users.ToList();
    }

使用GetRoles()和GetUsers()方法来填充下拉列表的两个示例。
public static void FillRoleDropDownList(DropDownList ddlParm)
{
    IEnumerable<IdentityRole> IERole = GetAllRoles();

    foreach (IdentityRole irRole in IERole)
    {
        ListItem liItem = new ListItem(irRole.Name, irRole.Id);
        ddlParm.Items.Add(liItem);
    }
}

public static void FillUserDropDownList(DropDownList ddlParm)
{ 
    IEnumerable<IdentityUser> IEUser = GetAllUsers();

    foreach (IdentityUser irUser in IEUser)
    {
        ListItem liItem = new ListItem(irUser.UserName, irUser.Id);
        ddlParm.Items.Add(liItem);
    }
}

使用示例:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillRoleDropDownList(ddlRoles);
            FillUserDropDownList(ddlUser);
        }
    }

感谢Anthony和Alex帮助我理解这些身份类。

-1

System.Web.Security 的 Roles 类还允许获取角色列表。

List<String> roles = System.Web.Security.Roles.GetAllRoles();


3
这个类是在 Asp.Net Identity 出现之前就存在了。 - Bellash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接