/* Adding a user to a role using UserStore */ var userStore = new UserStore(new ApplicationDbContext()); var userManager = new UserManager (userStore); var user = await userManager.FindByNameAsync("[email protected]"); await userManager.AddToRoleAsync(user.Id, "Admin");
/* Using dependency injection to add a user to a role */ public class AccountController : Controller { private readonly UserManagerIn this example, the UserManager object is injected into the AccountController class using dependency injection. The AddUserToRole method is decorated with the [Authorize] attribute, which restricts access to this method to users who are members of the "Admin" role. The method retrieves the user object using the FindByIdAsync method, and adds the user to the "User" role using the AddToRoleAsync method. The package library for the UserStore and UserManager classes is Microsoft.AspNet.Identity.EntityFramework._userManager; public AccountController(UserManager userManager) { _userManager = userManager; } [HttpPost] [Authorize(Roles = "Admin")] public async Task AddUserToRole(string userId) { var user = await _userManager.FindByIdAsync(userId); await _userManager.AddToRoleAsync(user, "User"); return RedirectToAction("Index", "Admin"); } }