【问题标题】:Stop AspNet Identity storing email address after validation error验证错误后停止 AspNet Identity 存储电子邮件地址
【发布时间】:2016-12-13 01:48:59
【问题描述】:

我有一个从旧系统中获取用户列表并同步我的 AspNet Identity 数据库的服务。我在使用 UserManager.SetEmail(string userId, string email) 更新用户的电子邮件地址时遇到问题,并且验证失败。 UserStore 中的用户对象保留了无效电子邮件地址的值。我停止处理该用户并跳到列表中的下一个用户。稍后,当我的服务找到要创建的新用户时,我使用 UserManager.Create(ApplicationUser user) 并使用所有未完成的更改更新数据库,包括现有用户的无效电子邮件地址。

有没有办法阻止无效的电子邮件地址被保留?这是一个错误还是我没有正确使用它?如果 IdentityResult 有错误,我是否应该在任何更新之前手动备份每个对象并恢复所有值?

//get LegacyUsers
foreach (AppUser appUser in LegacyUsers){
    var user = UserManager.FindByName(appUser.userName);
    if (user != null){
        If (!user.Email.Equals(appUser.Email)){
            var result = UserManager.setEmail(user.Id, appUser.Email)
            if (!result.Succeeded){
                //user object still has new value of email despite error, but not yet persisted to DB.
                Log.Error(…);
                continue;
            }
        }
    }
    else 
    {
        ApplicationUser newUser = new ApplicationUser{
            UserName = appUser.userName,
            //etc
        }
        var result = UserManager.Create(newUser);  //DB updates first user with new email aswell as inserting this new user 
        if (!result.Succeeded){
            Log.Error(…);
            continue;
        }
    }
}

我正在使用 Microsoft.AspNet.Identity.Core 和 Microsoft.AspNet.Identity.EntityFramework 的 2.2.1.40403 版本

【问题讨论】:

    标签: c# entity-framework-6 asp.net-identity-2


    【解决方案1】:

    发生这种情况是因为当SaveChanges() 方法被UserManager.Create() 方法调用时,EF 会跟踪模型并更新所有修改的对象。您可以像这样轻松地将具有无效电子邮件的用户从DbContext 中分离出来:

    // first get DbContext from the Owin.
    var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
    
    foreach (AppUser appUser in LegacyUsers){
        var user = UserManager.FindByName(appUser.userName);
        if (user != null){
            If (!user.Email.Equals(appUser.Email)){
                var result = UserManager.setEmail(user.Id, appUser.Email)
                if (!result.Succeeded){                
                    Log.Error(…);
                    // detach the user then proceed to the next one 
                    context.Entry(user).State = EntityState.Detached;
                    continue;
                }
            }
        }
        else{
            // rest of the code
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2018-05-26
      • 2018-03-13
      • 2011-09-02
      • 2013-02-20
      • 2014-03-12
      • 1970-01-01
      相关资源
      最近更新 更多