var userId = "abc123"; var roleName = "Admin"; // Retrieve the user from the manager var user = await UserManager.FindByIdAsync(userId); // Add the user to the specified role var result = await UserManager.AddToRoleAsync(userId, roleName); if (result.Succeeded) { // Role added successfully } else { // Error adding role }
[Authorize(Roles = "Admin")] public ActionResult DeleteUser(string userId) { // Delete user logic here return RedirectToAction("Index", "User"); }In this example, we have an action method that requires the user to be in the "Admin" role in order to perform a delete operation on a user. We use the [Authorize] attribute to require the specified role. The ApplicationUserManager class and the AddToRole() method are part of the Microsoft.AspNet.Identity.Core package, which is included in ASP.NET Identity.