Back to: ASP.NET Core Identity Tutorials
How to Delete Identity User in ASP.NET Core
In this article, I will discuss How to Delete ASP.NET Core Identity User. Please read our previous article discussing How to Edit Identity Users in ASP.NET Core.
How do you delete an identity user in ASP.NET Core?
Deleting a user in ASP.NET Core using the Identity framework involves setting up a controller action that handles the deletion request and then updating the database accordingly. So, deleting a user in ASP.NET Core when using Identity involves a few steps. They are as follows:
- Find the User: First, we need to find the user we want to delete. The UserManager service provides the FindByIdAsync or FindByEmailAsync methods for this purpose.
- Delete the User: Once we have the user, we can delete using the DeleteAsync method which is provided by the UserManager class. This method takes the user object as a parameter that we want to delete.
- Handle the Result: The DeleteAsync method returns a Task<IdentityResult>. You should await this task and then check if the deletion was successful.
Delete User in ASP.NET Core Identity:
Now, we will see how to delete an Identity User from the AspNetUsers database table using ASP.NET Core Identity. Deleting a User in ASP.NET Core Identity involves finding the user by ID, Email, or User Name (using any unique identifier) and removing it using the UserManager service.
In our example, in the ListUsers View, when the Delete button is clicked, the respective user must be deleted from the AspNetUsers table. When the user clicks the Delete button on the ListUsers Page, we want to display a delete confirmation message. The following is our ListUsers page displaying all the Roles.
When the user clicks on the Delete button, we want to display the delete confirmation message with Yes and No options, as shown in the below image:
When the user clicks the Yes button, the user must be deleted from the AspNetUsers database table and redirected to the ListUsers page. If the user clicks on the No option, then it should stay on the same page. Let us proceed and see how we can implement this.
Modifying ListUsers View:
First, modify the ListUsers.cshtml view as follows. Here, we add JavaScript code to show and hide the Delete and Yes or No buttons with the delete confirmation message when the user clicks the Delete button.
@model IEnumerable<ApplicationUser> @{ ViewBag.Title = "All Users"; } <h1>All Users</h1> @if (Model.Any()) { <a asp-action="Register" asp-controller="Account" class="btn btn-primary mb-3" style="width:auto"> Add New User </a> foreach (var user in Model) { <div class="card mb-3"> <div class="card-header"> User Id : @user.Id </div> <div class="card-body"> <h5 class="card-title">@user.UserName</h5> </div> <div class="card-footer"> <form method="post" asp-action="DeleteUser" asp-route-UserId="@user.Id"> <a asp-controller="Administration" asp-action="Edituser" asp-route-UserId="@user.Id" class="btn btn-primary">Edit</a> <span id="confirmDeleteSpan_@user.Id" style="display:none"> <span>Are you sure you want to Delete?</span> <button type="submit" class="btn btn-danger">Yes</button> <a href="#" class="btn btn-primary" onclick="confirmDelete('@user.Id', false)">No</a> </span> <span id="deleteSpan_@user.Id"> <a href="#" class="btn btn-danger" onclick="confirmDelete('@user.Id', true)">Delete</a> </span> </form> </div> </div> } } else { <div class="card"> <div class="card-header"> No Users Added Yet </div> </div> } <script> function confirmDelete(uniqueId, isDeleteClicked) { var deleteSpan = 'deleteSpan_' + uniqueId; var confirmDeleteSpan = 'confirmDeleteSpan_' + uniqueId; if (isDeleteClicked) { $('#' + deleteSpan).hide(); $('#' + confirmDeleteSpan).show(); } else { $('#' + deleteSpan).show(); $('#' + confirmDeleteSpan).hide(); } } </script>
In the above code,
- The span elements surrounding the Delete, Yes, and No buttons will be dynamically generated for every user on the list page.
- If you have more than one user on the page, there will be more than one span element.
- To ensure these span elements have unique IDs, we are appending User.Id, which is a Guid and guaranteed to be unique
- The Delete button (option yes) type is set to submit. It is placed inside the form element, and the method attribute is set to post.
- So, when the Yes button is clicked, a POST request is issued to the DeleteUser() action method, passing it the User ID to delete.
Adding DeleteUser Post Action Method:
Next, add the following DeleteUser Post action method to the AdministrationController. This method will delete the user, and on successful deletion, it will redirect to the ListUsers view. It will stay in the same view in case of any error by displaying error messages.
[HttpPost] public async Task<IActionResult> DeleteUser(string UserId) { //First Fetch the User you want to Delete var user = await _userManager.FindByIdAsync(UserId); if (user == null) { // Handle the case where the user wasn't found ViewBag.ErrorMessage = $"User with Id = {UserId} cannot be found"; return View("NotFound"); } else { //Delete the User Using DeleteAsync Method of UserManager Service var result = await _userManager.DeleteAsync(user); if (result.Succeeded) { // Handle a successful delete return RedirectToAction("ListUsers"); } else { // Handle failure foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return View("ListUsers"); } }
Understanding DeleteAsync Method:
In ASP.NET Core Identity, the DeleteAsync method of the UserManager<TUser> class is used to delete a User. The method takes the user entity to be deleted as an input parameter, typically an instance of IdentityUser or a class derived from it. The method returns Task<IdentityResult>. IdentityResult indicates the result of the identity operation. It contains information about whether the operation was successful and any errors that occurred.
With these changes in place, run the application and test the delete functionality, and it should work as expected.
Points to Remember:
- Permissions and Security: Delete a user should be protected by appropriate permissions. Typically, only administrators should be able to delete users.
- Data Integrity: Ensure that deleting a user does not violate database integrity constraints. For example, if the user has related data in other tables, you might need to handle that before deleting the user.
In the next article, I will discuss How to Enforce ON DELETE NO ACTION in ASP.NET Core Identity. In this article, I explain How to Delete Identity User in ASP.NET Core. I hope you enjoy this article, How to Delete Identity User in ASP.NET Core.