我在VS 2013中创建了一个新项目。我正在使用身份验证系统,但是我不知道如何获取应用程序中所有用户和所有角色的列表。我正在尝试创建一些管理页面,以便我可以添加新角色,将角色添加到用户中,查看谁已登录或锁定。
有人知道如何做到这一点吗?
我在VS 2013中创建了一个新项目。我正在使用身份验证系统,但是我不知道如何获取应用程序中所有用户和所有角色的列表。我正在尝试创建一些管理页面,以便我可以添加新角色,将角色添加到用户中,查看谁已登录或锁定。
有人知道如何做到这一点吗?
var context = new ApplicationDbContext();
var allUsers = context.Users.ToList();
var allRoles = context.Roles.ToList();
在 ASP.NET Identity 2.0(目前处于 Alpha 版本),此功能可在 UserManager
和 RoleManager
上使用...userManager.Users.ToList();
roleManager.Roles.ToList();
在两个版本中,您将与RoleManager
和UserManager
进行交互,以创建角色并将角色分配给用户。在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();
}
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();
}
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);
}
}
System.Web.Security 的 Roles 类还允许获取角色列表。
List<String> roles = System.Web.Security.Roles.GetAllRoles();