MVC 5身份更新UserRoles

时间:2015-04-27 15:05:40

标签: asp.net-mvc

我写了这段代码:

using(var _db = new ApplicationDbContext())
{
    string roleName = "Admin";
    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

    if(!roleManager.RoleExists(roleName))
    {
        var newRoleresult = roleManager.Create(new IdentityRole()
        {
            Name = roleName,
        });                  

        var userRole = new IdentityUserRole
        {                                        
            UserId = System.Web.HttpContext.Current.User.Identity.GetUserId(),
                        RoleId = roleManager.FindByName(roleName).Id,                    
        };

我只需要将userRole保存到表AspNetUserRoles。我怎么做?

1 个答案:

答案 0 :(得分:1)

要将UserRole相关联,您需要使用AddToRole方法UserManager API:

public async Task<ActionResult> UserRole()
    {
            string roleName = "Admin";
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            if (!roleManager.RoleExists(roleName))
            {
                var newRoleresult = await roleManager.CreateAsync(new IdentityRole()
                {
                    Name = roleName,
                });
                var result = await UserManager.AddToRoleAsync(
                    System.Web.HttpContext.Current.User.Identity.GetUserId(),
                    roleManager.FindByName(roleName).Name);
                if (!result.Succeeded)
                {
                    ModelState.AddModelError("", result.Errors.First().ToString());
                }
            }
        return View(); // If you have
    }