Adding Role dynamically in new VS 2013 Identity UserManager

醉酒当歌 提交于 2019-11-28 22:05:09
Ungaro

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);
            }
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!