我正在关注本文,以删除Identity 2.0中的用户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,让你删除的用户从给定角色的能力(通过他的主要标识)。它还定义了几种Find方法,例如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中使用“个人帐户”创建新项目时,可以找到如何执行此操作的示例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句