在新添加的角色动态VS 2013的UserManager身份 [英] Adding Role dynamically in new VS 2013 Identity UserManager

查看:379
本文介绍了在新添加的角色动态VS 2013的UserManager身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了新的VS2013 IDE一个新的MVC应用程序。我添加以下内容上的AccountController登录操作,我想创建一个动态默认用户:

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:

var admin = new ApplicationUser() { UserName = "administrator" };
var result = UserManager.Create(admin, "administrator");

这个伟大的工程,我当时就想要把这个默认的用户进入一个新的默认角色:

This works great, I then wanted to put this default user into a new default role:

user = UserManager.FindByName("administrator");
var roleresult = UserManager.AddToRole(user.Id,"admin");

第二行的错误,因为显然它无法找到角色管理员,因为它不存在,但我找不到的UserManager的相关方法这样做。我在哪里可以找到动态添加角色的方法?

The second line errors because obviously it can't find the role "admin" as it doesn't exist yet, but I can't find a relevant method on the UserManager to do so. Where can I find the method to add roles dynamically?

推荐答案

下面是我做到了。我有$ P $ {pauthorized用户名,角色}键字典的UserRole - 值对:

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);
            }
        }
}

这篇关于在新添加的角色动态VS 2013的UserManager身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆