Updating user role using asp.net identity

前端 未结 2 1329
挽巷
挽巷 2021-02-04 18:38

I have the following problem. While using the following code below to change the user\'s current role i am getting an exception with the message like below:

             


        
相关标签:
2条回答
  • 2021-02-04 18:56

    My roles are managed in the seed method of my DbMigrationsConfiguration class and I renamed it like this:

            if (context.Roles.Any(r => r.Name == "User"))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = manager.Roles.First(r => r.Name == "User");
    
                role.Name = "NewNameForUser";
                manager.Update(role);
            }
    
    0 讨论(0)
  • 2021-02-04 19:02

    The problem is that your Manager and DB doesn't use the same DbContext. So when you send an user from the context of your DB to the Manager it will handle it as a "new" one - and then you cant remove it from the role. You have two ways to go here. The easiest is to get the User from your Manager.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public virtual ActionResult Edit(User user, string role)
    {
        if (ModelState.IsValid)
        {
            // THIS LINE IS IMPORTANT
            var oldUser = Manager.FindById(user.Id);
            var oldRoleId = oldUser.Roles.SingleOrDefault().RoleId;
            var oldRoleName = DB.Roles.SingleOrDefault(r => r.Id == oldRoleId).Name;
    
            if (oldRoleName != role)
            {
                Manager.RemoveFromRole(user.Id, oldRoleName);
                Manager.AddToRole(user.Id, role);
            }
            DB.Entry(user).State = EntityState.Modified;
    
            return RedirectToAction(MVC.User.Index());
        }
        return View(user);
    }
    

    The more elegant way is to start using an DI-framework like AutoFac (https://code.google.com/p/autofac/wiki/MvcIntegration) and set your DbContext as InstancePerApiRequest.

    builder.RegisterType<YourDbContext>().As<DbContext>().InstancePerApiRequest();
    
    0 讨论(0)
提交回复
热议问题