Getting All Users and All Roles through asp.net Identity

后端 未结 4 1001
栀梦
栀梦 2020-12-18 21:34

I have a new project i created in VS 2013. I am using the identity system and i\'m confused how to get a list of all users to the application and all roles int he applicati

4条回答
  •  独厮守ぢ
    2020-12-18 22:21

    Building on Anthony Chu and Alex.
    Creating two helper classes...

        public class UserManager : UserManager
          {
            public UserManager() 
                : base(new UserStore(new ApplicationDbContext()))
                { }
           }
    
         public class RoleManager : RoleManager
         {
            public RoleManager()
                : base(new RoleStore(new ApplicationDbContext()))
            { }
          }
    

    Two methods to get the roles and users.

       public static IEnumerable GetAllRoles()
        {
            RoleManager roleMgr = new RoleManager();
            return roleMgr.Roles.ToList();
        }
    
        public static IEnumerable GetAllUsers()
        {
            UserManager userMgr = new UserManager();
            return userMgr.Users.ToList();
        }
    

    Two examples of Methods using GetRoles() and GetUsers() to populat a dropdown.

    public static void FillRoleDropDownList(DropDownList ddlParm)
    {
        IEnumerable 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 IEUser = GetAllUsers();
    
        foreach (IdentityUser irUser in IEUser)
        {
            ListItem liItem = new ListItem(irUser.UserName, irUser.Id);
            ddlParm.Items.Add(liItem);
        }
    }
    

    usage example:

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

    thx to Anthony and Alex for helping me understand these Identity classes.

提交回复
热议问题