0

I want to change the role of a user in my application.

I used Dependency Injection to access UserManager _usermanager in my controller. To change the role I'm supposed to call _usermanager.AddToRoleAsync(IdentityUser user, string role), but I can't seem to locate the a IdentityUser enity.

    [HttpPost]
    public async Task<IActionResult> BewerkGebruiker(int id , ... )
    {
        Gebruiker g;
        using (var context =  new UTILcontext())
        {
            _userManager.AddToRoleAsync(<<what do i put here?>>),Rol);
            _manager.UpdateGebruiker(g);
            return RedirectToAction("Gebruikers");
        };
wlf
  • 23
  • 5
  • Possible duplicate of [How to create roles in asp.net core and assign them to users](https://stackoverflow.com/questions/42471866/how-to-create-roles-in-asp-net-core-and-assign-them-to-users) – William Xifaras May 29 '19 at 00:41

2 Answers2

1

I didn't know about the _userManager.Users Property. This way I can find the right IdentityUser to fill the AddToRoleAsync with.

Problem solved!

wlf
  • 23
  • 5
0

Something like this should work. AppUser is a class derived from Microsoft.AspNetCore.Identity.IdentityUser that you would typically have in your Models directory.

[HttpPost]
public async Task<IActionResult> EditUser(int userId, string roleName, ...)
{
     AppUser user = await userManager.FindByIdAsync(model.Id);

     if (user != null)
         IdentityResult result = await userManager.AddToRoleAsync(user, roleName);
    . . . 
}
Martin
  • 87
  • 1
  • 5