Asp.net
通過 asp.net Identity 獲取所有使用者和所有角色
我有一個在 VS 2013 中創建的新項目。我正在使用身份系統,我很困惑如何獲取應用程序的所有使用者列表以及應用程序中的所有角色。我正在嘗試創建一些管理頁面,以便我可以添加新角色、向使用者添加角色、查看所有登錄或鎖定的使用者。
有人知道怎麼做嗎?
在 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 版)中,此功能在
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(); }