How to delete user with UserManager in mvc5

10,220

Solution 1

Delete was not supported in UserManager in 1.0, but its supported in the upcoming 2.0 release, and in the current 2.0 nightly builds if you want to preview the changes early.

Solution 2

I had issues with the above answer, though I was able to work out what's wrong. I kept getting a cascading error. Basically the user was being deleted without the role being deleted. DeleteAsync was not doing that for me (I have the latest build of Identity Framework). Ended up passing both the userid and role into my code, deleting the user from the role, then deleting the user. Seems to work fine.

[HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Delete(string id, string role)
    {
        // Check for for both ID and Role and exit if not found
        if (id == null || role == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        // Look for user in the UserStore
        var user = UserManager.Users.SingleOrDefault(u => u.Id == id);

        // If not found, exit
        if (user == null)
        {
            return HttpNotFound();
        }

        // Remove user from role first!
        var remFromRole = await UserManager.RemoveFromRoleAsync(id, role);

        // If successful
        if (remFromRole.Succeeded)
        {
            // Remove user from UserStore
            var results = await UserManager.DeleteAsync(user);

            // If successful
            if (results.Succeeded)
            {
                // Redirect to Users page
                return RedirectToAction("Index", "Users", new {area = "Dashboard"});
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
        }
        else
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

    }
Share:
10,220
Gandalf
Author by

Gandalf

Updated on June 04, 2022

Comments

  • Gandalf
    Gandalf almost 2 years

    I'm using mvc5, and everything about user account management I do with UserManager. It works good with roles, claims, etc. But I didn't find how to delete user with UserManager. Is there a way to delete user with UserManager? I can create Database context with dbset and then delete it from this context, but I don't want create dbcontext, userclass, etc. for one delete method.

  • Gandalf
    Gandalf almost 10 years
    Yes, it is possible now, when released update identity 2.0.0. I'm using it