Back to: ASP.NET MVC Tutorial For Beginners and Professionals
How to Add, Update, and Delete Roles in ASP.NET Identity
This article will discuss How to Add, Update, and Delete Roles in ASP.NET Identity with Examples. Kindly look at our previous article, where we discussed the basic concepts of Roles Management in ASP.NET Identity.
How to Add Role in ASP.NET Identity?
To add a new role in ASP.NET Identity, we need to use the Create or CreateAsync method of the ApplicationRoleManager instance.
Create or CreateAsync Method
The Create or CreateAsync method creates the role passed as a parameter and returns the result of the operation as an IdentityResult object.
IdentityResult result = RoleManager.Create(role);
Instead of using Create method, we can also use the CreateAsync method as follows:
IdentityResult result = await RoleManager.CreateAsync(role);
The Create or CreateAsync method is called by the RoleManager, responsible for performing the role-related operations in ASP.NET Identity.
RoleManager
We use the Get method to get the ApplicationRoleManager from the OwinContext as follows:
ApplicationRoleManager RoleManager = HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
Example to Understand Add Role in ASP.NET Identity:
Let us first add the following RegisterRoleViewModel inside the Models folder. The RegisterRoleViewModel object is the ViewModel we use to render and validate the AddRole view.
using System.ComponentModel.DataAnnotations; namespace AspNetIdentityWithNewProject.Models { public class RegisterRoleViewModel { [Display(Name = "Role name")] [Required] public string RoleName { get; set; } } }
In our previous session, we created the Roll Controller. Let us modify the Roll Controller as follows. Here, you can see we have added one method, which is going to add a Role.
using AspNetIdentityWithNewProject.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using System.Web; using System.Web.Mvc; namespace AspNetIdentityWithNewProject.Controllers { public class RollController : Controller { private ApplicationRoleManager _roleManager; public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } [HttpPost] public ActionResult AddRole(RegisterRoleViewModel model) { if (ModelState.IsValid) { IdentityRole role = new IdentityRole { Name = model.RoleName }; IdentityResult result = RoleManager.Create(role); if (result.Succeeded) { string RoleId = role.Id; return RedirectToAction("Index", "Home", new { Id = RoleId }); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } } }
In the above code, we receive the details of the role to be created through an HTTP Post request. We then create a fresh IdentityRole object and pass it as an argument to the Create method to form a new role. Subsequently, we verify the operation’s success by accessing the Succeeded property of the IdentityResult object. If it fails, we iterate through the Errors list and append them to the ModelState using the AddModelError method.
Namespaces
To use the Get method, the Create method, the IdentityResult object, and the IdentityRole object, you have to include the following namespaces:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
How to Update Role in ASP.NET Identity?
In order to update an existing role in ASP.NET Identity, we need to use the Update or UpdateAsync method of the ApplicationRoleManager instance.
Update or UpdateAsync Method
The Update or UpdateAsync method updates the role passed as a parameter and returns the result of the operation as an IdentityResult object.
IdentityResult result = RoleManager.Update(role);
Instead of using the Update method, we can also use the UpdateAsync method as follows:
IdentityResult result = await RoleManager.UpdateAsync(role);
The Update or UpdateAsync method is called by the RoleManager, which is responsible for performing the role-related operations in ASP.NET Identity.
Example to Understand Update Role in ASP.NET Identity:
Let us first add the following EditRoleViewModel inside the Models folder. The EditRoleViewModel object is the ViewModel we use to render and validate the UpdateRole view.
using System.ComponentModel.DataAnnotations; namespace AspNetIdentityWithNewProject.Models { public class EditRoleViewModel { [Required] public string RoleId { get; set; } [Display(Name = "Role name")] [Required] public string RoleName { get; set; } } }
Next, modify the Roll Controller as follows. Here, you can see we have added another HTTP Post method called UpdateRole, which is basically going to update a Role.
using AspNetIdentityWithNewProject.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using System.Web; using System.Web.Mvc; namespace AspNetIdentityWithNewProject.Controllers { public class RollController : Controller { private ApplicationRoleManager _roleManager; public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } [HttpPost] public ActionResult AddRole(RegisterRoleViewModel model) { if (ModelState.IsValid) { IdentityRole role = new IdentityRole { Name = model.RoleName }; IdentityResult result = RoleManager.Create(role); if (result.Succeeded) { string RoleId = role.Id; return RedirectToAction("Index", "Home", new { Id = RoleId }); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } [HttpPost] public ActionResult UpdateRole(EditRoleViewModel model) { if (ModelState.IsValid) { IdentityRole roleToEdit = RoleManager.FindById(model.RoleId); if (roleToEdit == null) { return HttpNotFound(); } if (roleToEdit.Name != model.RoleName) { roleToEdit.Name = model.RoleName; } IdentityResult result = RoleManager.Update(roleToEdit); if (result.Succeeded) { return RedirectToAction("Index", "Home", new { Id = model.RoleId }); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } } }
In the example above, we receive the information of the role to update through an HTTP Post request. We fetch the role details to update it by its id using the FindById method and then update the role using the Update method. To check if the operation was successful, we accessed the Succeeded property of the IdentityResult object. If it was not successful, we iterate through the list of Errors and add them to the ModelState using the AddModelError method.
How to Delete Role in ASP.NET Identity?
In order to delete an existing role in ASP.NET Identity, we need to use the Delete or DeleteAsync method of the ApplicationRoleManager instance.
Delete or DeleteAsync Method
The Delete or DeleteAsync method deletes the role passed as a parameter and returns the result of the operation as an IdentityResult object.
IdentityResult result = RoleManager.Delete(role);
Instead of using the Delete method, we can also use the DeleteAsync method as follows:
IdentityResult result = await RoleManager.DeleteAsync(role);
The Delete or DeleteAsync method is called by the RoleManager, which is responsible for performing the role-related operations in ASP.NET Identity.
Example to Understand Delete Role in ASP.NET Identity:
Let us first add the following DeleteRoleViewModel inside the Models folder. The DeleteRoleViewModel object is the ViewModel we use to render and validate the DeleteRole view.
using System.ComponentModel.DataAnnotations; namespace AspNetIdentityWithNewProject.Models { public class DeleteRoleViewModel { [Required] public string RoleId { get; set; } } }
Next, modify the Roll Controller as follows. Here, you can see we have added another HTTP Post method called DeleteRole, which is going to delete a Role.
using AspNetIdentityWithNewProject.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using System.Web; using System.Web.Mvc; namespace AspNetIdentityWithNewProject.Controllers { public class RollController : Controller { private ApplicationRoleManager _roleManager; public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } [HttpPost] public ActionResult AddRole(RegisterRoleViewModel model) { if (ModelState.IsValid) { IdentityRole role = new IdentityRole { Name = model.RoleName }; IdentityResult result = RoleManager.Create(role); if (result.Succeeded) { string RoleId = role.Id; return RedirectToAction("Index", "Home", new { Id = RoleId }); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } [HttpPost] public ActionResult UpdateRole(EditRoleViewModel model) { if (ModelState.IsValid) { IdentityRole roleToEdit = RoleManager.FindById(model.RoleId); if (roleToEdit == null) { return HttpNotFound(); } if (roleToEdit.Name != model.RoleName) { roleToEdit.Name = model.RoleName; } IdentityResult result = RoleManager.Update(roleToEdit); if (result.Succeeded) { return RedirectToAction("Index", "Home", new { Id = model.RoleId }); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } [HttpPost] public ActionResult DeleteRole(DeleteRoleViewModel model) { if (ModelState.IsValid) { IdentityRole roleToDelete = RoleManager.FindById(model.RoleId); if (roleToDelete == null) { return HttpNotFound(); } IdentityResult result = RoleManager.Delete(roleToDelete); if (result.Succeeded) { return RedirectToAction("Index", "Home"); } foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } return View(model); } } }
In the example above, we receive the details of the role to be deleted through an HTTP Post request. We use the FindById method to find the role to delete by its id, and then we utilize the Delete method to remove the role. To verify if the operation was successful, we examine the Succeeded property of the IdentityResult object. If it is not successful, we iterate through the Errors list and append them to the ModelState using the AddModelError method.
In the next article, I am going to discuss How to Assign a User to a Role in ASP.NET Identity with Examples. Here, in this article, I try to explain How to Add, Update, and Delete Roles in ASP.NET Identity with Examples. I hope you enjoy this Add, Update, and Delete Roles in the ASP.NET Identity article.