Delete a user account

Introduction


In order to delete a user account in ASP.NET Identity, we use the Delete method.

Delete


The Delete method deletes the user passed as a parameter of the method and returns the result of the operation as an IdentityResult object.

IdentityResult result = UserManager.Delete(UserToDelete);

The Delete method is called by the UserManager which is responsible for performing the user-related operations.

UserManager


We use the GetUserManager method to get the ApplicationUserManager from the OWIN context.

ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

We use the ApplicationUserManager instead of the UserManager in order to use the default validation logic for usernames and passwords configured in the IdentityConfig.cs file.

Namespaces


In order to use the GetUserManager method, the Delete method and the IdentityResult object, you have to include the following namespaces :

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

Example


[HttpPost]
public ActionResult DeleteUser(string Id)
{
    ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

    ApplicationUser UserToDelete = UserManager.FindById(Id);

    if (UserToDelete != null) {
        IdentityResult result = UserManager.Delete(UserToDelete);
        if (identityResult.Succeeded)
        {
            return RedirectToAction("Index", "Home");
        }

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

        return View(Id);
    }

    return HttpNotFound();
}

In the above example, we get the id of the user to delete via an HTTP Post request. We get the user manager from the OWIN context by using the GetUserManager method and then we use the FindById method to find the user to delete by its id. If the user does not exist, we return an HTTP 404 error page. Otherwise, we delete the user and 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 object by using the AddModelError method.

Find the user to delete


In addition to the FindById method, we can also use the FindByName method or the FindByEmail method to find the user to delete by its username or by its email address.