9079total visits.
UserManager defines a number of inbuilt method like FindAsync, FindByIdAsync, FindByNameAsync and FindByEmailAsync. These all can be used to retrieve and retrieve user details. UserManager also has DeleteAsync method which accepts a user object as a parameter and deletes the current user. To get the roles a user is the member of Identity gives UserManager has GetRolesAsync method where it accepts the ID of the user.
Also, UserManager.RemoveLoginAsync method removes a login from a user.
UserManager.RemoveFromRoleAsync: removes user from a Role
UserManager.FindAsync: Returns the user associated with this login.
UserManager.FindByIdAsync : Finds a user by ID.
UserManager.FindByNameAsync : Finds a user by username.
UserManager.FindByEmailAsync : Finds a user by e-mail.
Now let’s create a method called DeleteUser in ManageUsers Controller that accepts UserId as a parameter.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
public async Task<ActionResult> DeleteUserd(string userId) { if (userId == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } //get User Data from Userid var user = await UserManager.FindByIdAsync(userId); //List Logins associated with user var logins = user.Logins; //Gets list of Roles associated with current user var rolesForUser = await UserManager.GetRolesAsync(userId); using (var transaction = context.Database.BeginTransaction()) { foreach (var login in logins.ToList()) { await UserManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey)); } if (rolesForUser.Count() > 0) { foreach (var item in rolesForUser.ToList()) { // item should be the name of the role var result = await UserManager.RemoveFromRoleAsync(user.Id, item); } } //Delete User await UserManager.DeleteAsync(user); TempData["Message"] = "User Deleted Successfully. "; TempData["MessageValue"] = "1"; //transaction.commit(); } return RedirectToAction("UsersWithRoles", "ManageUsers", new { area = "", }); } |
The codes in above method is very simple and easy to understand.
Now let’s try deleting a user.
For now, I have added a delete Action Button on UsersWithRoles views as discussed in the previous example. [http://localhost:64303/ManageUsers/UsersWithRoles].

You can find full working Source Code at https://github.com/nishanaryal/ASP.NET-MVC