Adding Role dynamically in new VS 2013 Identity UserManager

后端 未结 1 650
陌清茗
陌清茗 2020-12-15 01:11

I created a new MVC application in the new VS2013 IDE. I added the following to the Login Action on the AccountController as I wanted to create a default user dynamically:

相关标签:
1条回答
  • 2020-12-15 01:58

    Here is how I did it. I have a Dictionary userRoles with preauthorized {userName, role} key - value pairs :

    private void setRoles()
    {
        using(var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())))
        using(var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
            foreach (var item in userRoles)
            {
                if (!rm.RoleExists(item.Value))
                {
                    var roleResult = rm.Create(new IdentityRole(item.Value));
                    if (!roleResult.Succeeded)
                        throw new ApplicationException("Creating role " + item.Value + "failed with error(s): " + roleResult.Errors);
                }
                var user = um.FindByName(item.Key);
                if (!um.IsInRole(user.Id, item.Value))
                {
                    var userResult = um.AddToRole(user.Id, item.Value);
                    if (!userResult.Succeeded)
                        throw new ApplicationException("Adding user '" + item.Key + "' to '" + item.Value + "' role failed with error(s): " + userResult.Errors);
                }
            }
    }
    
    0 讨论(0)
提交回复
热议问题