ASP.NET MVC 5 如何在 Identity 2.0 中删除用户及其相关数据 [英] ASP.NET MVC 5 how to delete a user and its related data in Identity 2.0

查看:31
本文介绍了ASP.NET MVC 5 如何在 Identity 2.0 中删除用户及其相关数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这篇文章以删除 Identity 2.0 中的用户http://www.asp.net/mvc/tutorials/mvc-5/introduction/examing-the-details-and-delete-methods

I'm following this article to delete a user in Identity 2.0 http://www.asp.net/mvc/tutorials/mvc-5/introduction/examining-the-details-and-delete-methods

但是,我需要先删除AspNetUserRoles中的所有相关记录,然后再删除用户.

However, I need to delete all related records in AspNetUserRoles first and then delete the user.

我发现了一个用 Identity 1.0 编写的示例,但该示例中使用的一些方法不存在.

I found an example which is written in Identity 1.0 and some of methods used inside this example don't exist.

   // 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() 方法.

I cannot find IdentityManager from anywhere, and context.Users doesn't have FindAsync() method either.

如何在 Identity 2.0 中正确删除用户及其相关记录?

How can I properly delete a User and its related records in Identity 2.0?

推荐答案

我认为您正在寻找的课程是 UserManagerRoleManager.在我看来,它们是更好的方法,而不是直接违背上下文.

I think the classes you're looking for are the UserManager and the RoleManager. In my opinion they are the better way instead of going against the context directly.

UserManager 定义了一个方法 RemoveFromRoleAsync 这使您能够从给定角色中删除用户(由其密钥标识).它还定义了几个 Find 方法,例如 FindAsyncFindByIdAsyncFindByNameAsyncFindByEmailAsync.它们都可用于检索用户.要删除用户,您应该使用 DeleteAsync 接受用户对象作为参数的方法.要获得用户是身份成员的角色,请为您提供 GetRolesAsync 方法,您可以在其中传递用户的 ID.我还看到您正在尝试从用户中删除登录名.为此,您应该使用 RemoveLoginAsync方法.

The UserManager defines a method RemoveFromRoleAsync which gives you the ability to remove the user (identified by his key) from a given role. It also defines several Find methods, such as FindAsync, FindByIdAsync, FindByNameAsync, or FindByEmailAsync. They all can be used to retrieve a user. To delete a user you should use the DeleteAsync method which accepts a user object as a parameter. To get the roles a user is member of Identity gives you the GetRolesAsync method where you pass in the ID of the user. Also I see that you're trying to remove a login from a user. For this purpose you should use the RemoveLoginAsync method.

总的来说,您的代码将类似于以下代码:

All in all your code would look similar to the following one:

// 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 中创建新项目时,可以找到如何执行此操作的示例.

You'll need to adjust this snippet to your needs, because I don't have an idea how your IdentityUser implementation looks like. Remember to declare the UserManager as needed. An example how you could do this can be found when you create a new project in Visual Studio using Individual Accounts.

这篇关于ASP.NET MVC 5 如何在 Identity 2.0 中删除用户及其相关数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆