Reputation: 1602
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.
Upvotes: 0
Views: 202
Reputation: 1064
In the Role Controller class, You have to add a dependency of RoleManager
class to the Constructor.
The RoleManager
class is used to manage the Roles in Identity, and has the some important functions and properties. The role
is an object of type IdentityRole
.
Example of creating and deleting roles:
[HttpPost]
public async Task<IActionResult> Create([Required]string name)
{
if (ModelState.IsValid)
{
IdentityResult result = await roleManager.CreateAsync(new IdentityRole(name));
if (result.Succeeded)
return RedirectToAction("Index");
else
Errors(result);
}
return View(name);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
IdentityRole role = await roleManager.FindByIdAsync(id);
if (role != null)
{
IdentityResult result = await roleManager.DeleteAsync(role);
if (result.Succeeded)
return RedirectToAction("Index");
else
Errors(result);
}
else
ModelState.AddModelError("", "No role found");
return View("Index", roleManager.Roles);
}
Then you can use the following members of the UserManager
class to play with the roles:
userManager.AddToRoleAsync(AppUser user, string name)
userManager.RemoveFromRoleAsync(AppUser user, string name)
etc.
You can read full arcticle here
Upvotes: 0
Reputation: 1540
Try this:
await userManager.RemoveFromRoleAsync(oldAdminUser, "GroupAdmin");
await userManager.RemoveFromRoleAsync(newAdminUser, "GroupUser");
await userManager.AddToRoleAsync(oldAdminUser, "GroupUser");
await userManager.AddToRoleAsync(newAdminUser, "GroupAdmin");
Upvotes: 1