Search code examples
c#asp.net-core-identityasp.net-core-3.1

How can I remove/add a role from/to a user?


This is how I want it to work. How does it work?

userManager.RemoveRole(oldAdminUser, "GroupAdmin");
userManager.RemoveRole(newAdminUser, "GroupUser");
userManager.AddRole(oldAdminUser, "GroupUser");
userManager.AddRole(newAdminUser, "GroupAdmin");

In the fantasy example above, two users swap roles. The old admin becomes a user, and the old user becomes the admin.


Solution

  • Try this:

    await userManager.RemoveFromRoleAsync(oldAdminUser, "GroupAdmin");
    await userManager.RemoveFromRoleAsync(newAdminUser, "GroupUser");
    await userManager.AddToRoleAsync(oldAdminUser, "GroupUser");
    await userManager.AddToRoleAsync(newAdminUser, "GroupAdmin");