Back to: ASP.NET MVC Tutorial For Beginners and Professionals
How to Assign a User to a Role in ASP.NET Identity
In this article, I am going to discuss How to Assign a User to a Role in ASP.NET Identity with Examples. Kindly take a look at our previous article, where we discussed the basic concepts of How to Add, Update, and Delete Roles in ASP.NET Identity.
How to Assign a User to a Role in ASP.NET Identity?
To assign a role to a user in ASP.NET Identity, we need to use the AddToRole or AddToRoleAsync method. The AddToRole or AddToRoleAsync method will add the user to the specified role and provide the outcome of the action as an IdentityResult object.
IdentityResult result = UserManager.AddToRole(userId, roleName);
IdentityResult result = await UserManager.AddToRoleAsync(userId, roleName);
Note: The AddToRole or AddToRoleAsync method is called by the UserManager, which is responsible for performing the user-related operations in ASP.NET Identity.
UserManager In ASP.NET Identity:
In ASP.NET Identity, we need to use the GetUserManager method to get the ApplicationUserManager from the Owin context as follows.
ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Example to Add a User to a Role in ASP.NET Identity:
So, you can use the following HTTP Post action method in ASP.NET MVC Application to add a User to a Role using ASP.NET Identity.
[HttpPost] public ActionResult AssignUserToRole(string userId, string roleName) { ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); IdentityResult result = UserManager.AddToRole(userId, roleName); if (result.Succeeded) { //Whichever Page you want, you can redirect return RedirectToAction("Index", "Home"); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } return View(); }
The code example above shows how to declare an HTTP Post action method with two parameters: the user ID and the role name we want to assign to the user. Then, we use the AddToRole method to add the user to the specified role and return the result. After that, we check the success of the operation by accessing the Succeeded property of the IdentityResult object. If the operation fails, we iterate through the Errors list and append them to the ModelState using the AddModelError method.
Namespaces:
In order to use the GetUserManager method, the AddToRole method, and the IdentityResult object, you have to include the following two namespaces:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
In the next article, I am going to discuss How to Get User Roles in ASP.NET Identity with Examples. In this article, I explain How to Assign a User to a Role in ASP.NET Identity with Examples. I hope you enjoy this Assign a User to a Role in the ASP.NET Identity article.