Introduction
In order to delete an existing role in ASP.NET Identity, we use the Delete method.
Delete
The Delete method deletes the role passed as a parameter and returns the result of the operation as
an IdentityResult
object.
IdentityResult result = RoleManager.Delete(role);
The Delete method is called by the RoleManager, which is responsible for performing the role-related operations.
RoleManager
We use the Get method to get the ApplicationRoleManager from the OwinContext.
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
Check the Roles management section, for more information about the configuration of the RoleManager.
Example
[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 above example, we get the information of the role to delete via an HTTP Post request. We
use the FindById method to find the role to delete by its id and then we use
the Delete method in order to delete this role. We access the Succeeded
property of
the IdentityResult object to check if the opration was successful. If it is not the case, we loop
through the list of Errors
and we add them to the ModelState by using the AddModelError
method.
The DeleteRoleViewModel
object is the ViewModel that we are using in order to render and validate the
DeleteRole view.
public class DeleteRoleViewModel
{
[Required]
public string RoleId { get; set; }
}
Namespaces
In order to use the Get method, the Delete 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;