Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Delete identity user in core

Suggested Videos
Part 83 - Show or hide navigation menu based on user role in core | Text | Slides
Part 84 - List all users from core identity database | Text | Slides
Part 85 Edit identity user in core | Text | Slides

In this video we will discuss how to delete IdentityUser from the AspNetUsers database table using the Identity API.

When the Delete button is clicked, the respective user must be deleted from the AspNetUsers table 

Deleting data using a GET request is not recommended.

Just imagine what can happen if there is an image tag in a malicious email as shown below. The moment we open the email, the image tries to load and issues a GET request, which would delete the data.

<img src="http://localhost/Administration/DeleteUser/123" />

Also, when search engines index your page, they issue a GET request which would delete the data. In general GET request should be free of any side-effects, meaning it should not change the state on the server. Deletes should always be performed using a POST request.

Deleting data using a POST request
  • Delete button type is set to submit
  • It is placed inside the form element and the method attribute is set to post
  • So when the Delete button is clicked a POST request is issued to DeleteUser() action passing it the ID of the user to delete
<form method="post" asp-action="DeleteUser" asp-route-id="@user.Id">
    <button type="submit" class="btn btn-danger">Delete</button>

DeleteUser Action in the Controller

Use the UserManager service DeleteAsync() method to delete the user

public class AdministrationController : Controller
    private readonly UserManager<ApplicationUser> userManager;

    public AdministrationController(UserManager<ApplicationUser> userManager)
        this.userManager = userManager;

    public async Task<IActionResult> DeleteUser(string id)
        var user = await userManager.FindByIdAsync(id);

        if (user == null)
            ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
            return View("NotFound");
            var result = await userManager.DeleteAsync(user);

            if (result.Succeeded)
                return RedirectToAction("ListUsers");

            foreach (var error in result.Errors)
                ModelState.AddModelError("", error.Description);

            return View("ListUsers");
} core tutorial for beginners

No comments:

Post a Comment

It would be great if you can help share these free resources