嗨,我正在关注本文删除Identity 2.0中的用户
http://www.asp.net/mvc/tutorials/mvc-5/introduction/examining-the-details-and-delete-methods
http://www.asp.net/mvc/tutorials/mvc-5/introduction/examining-the-details-and-delete-methods
但是,我需要先删除AspNetUserRoles中的所有相关记录,然后删除该用户.
我发现一个写在Identity 1.0中的例子,这个例子中使用的一些方法不存在.
- // POST: /Users/Delete/5
- [HttpPost,ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> DeleteConfirmed(string id)
- {
- if (ModelState.IsValid)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var user = await context.Users.FindAsync(id);
- var logins = user.Logins;
- foreach (var login in logins)
- {
- context.UserLogins.Remove(login);
- }
- var rolesForUser = await IdentityManager.Roles.GetRolesForUserAsync(id,CancellationToken.None);
- if (rolesForUser.Count() > 0)
- {
- foreach (var item in rolesForUser)
- {
- var result = await IdentityManager.Roles.RemoveUserFromRoleAsync(user.Id,item.Id,CancellationToken.None);
- }
- }
- context.Users.Remove(user);
- await context.SaveChangesAsync();
- return RedirectToAction("Index");
- }
- else
- {
- return View();
- }
- }
我从任何地方找不到“IdentityManager”,context.Users也没有FindAsync()方法.
请帮忙弄清楚如何在Identity 2.0中正确删除用户及其相关记录
谢谢.
解决方法
我认为你正在寻找的课程是
UserManager和
RoleManager.在我看来,他们是更好的方式,而不是直接反对上下文.
UserManager定义了一个方法RemoveFromRoleAsync,它允许您从给定角色中删除用户(由他的密钥识别).它还定义了几种查找方法,例如FindAsync,FindByIdAsync,FindByNameAsync或FindByEmailAsync.它们都可以用于检索用户.要删除用户,您应该使用接受用户对象作为参数的DeleteAsync方法.要获取用户是Identity的成员角色,您可以通过GetRolesAsync方法传递用户的ID.此外,我看到您正在尝试从用户中删除登录.为此,您应该使用RemoveLoginAsync方法.
- // POST: /Users/Delete/5
- [HttpPost,ActionName("Delete")]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> DeleteConfirmed(string id)
- {
- if (ModelState.IsValid)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var user = await _userManager.FindByIdAsync(id);
- var logins = user.Logins;
- var rolesForUser = await _userManager.GetRolesAsync(id);
- 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);
- }
- }
- await _userManager.DeleteAsync(user);
- transaction.commit();
- }
- return RedirectToAction("Index");
- }
- else
- {
- return View();
- }
- }
您需要根据需要调整此片段,因为我不知道IdentityUser实现如何.请记住根据需要声明UserManager.在Visual Studio中使用个人帐户创建新项目时,可以找到一个可以做到这一点的示例.