AspNetCore.Identity重置密码 - ' X'的实例无法跟踪

时间:2017-06-15 14:11:48

标签: c# asp.net-core entity-framework-core invalidoperationexception asp.net-core-identity

我尝试使用AspNetCore.Identity程序集实现密码重置机制。首先是用户说他们忘记了密码,输入了他们的电子邮件和密码,然后提交。最终调用此代码

IdentUser user = UserManager.FindByName(passwordObj.username);

//Some unrelated code in between

Task<string> codeTask = UserManager.GeneratePasswordResetTokenAsync(user);

string code = Base64ForUrlEncode(codeTask.Result);
string applicationUrl = string.Format("{0}/{1}?userId={2}&&token={3}", ApplicationUrl, "ResetPasswordView", user.Id, code);

我在生成重置密码令牌时没有任何问题,任务运行完成,我收到一封包含正确网址的电子邮件。

但是,当我尝试重置密码时,我会看到这段代码

public JsonResult ResetPassword(ResetPasswordModel passwordObj)
{
    IdentUser User = UserManager.FindById(passwordObj.userId);

    //Unrelated code

    Task<IdentityResult> resetPassTask = UserManager.ResetPasswordAsync(User, Base64ForUrlDecode(passwordObj.token), passwordObj.resetPassword);
    IdentityResult user = resetPassTask.Result;

....
}

并且resetPassTask.Result行正在生成一个例外,说明&#34; 实体类型的实例&#39; IdentUser&#39;无法跟踪,因为已经跟踪了具有相同密钥的此类型的另一个实例

我还是相对较新的ASP.NET Core,我刚刚开始学习异步调用的来龙去脉,所以我很难调试这个。我一直在寻找答案,并且找不到任何解决我问题的方法,所以我在这里。有关如何修复或调试此问题的任何想法?

1 个答案:

答案 0 :(得分:0)

所以,我想出了我的问题,并发布了我的修复程序,以便希望能够帮助其他人面对这个问题。

我的FindById函数是在AspNetCore.Identity的UserManager IdentUserManager的扩展中实现的。 FindById不是异步的 - &gt;

public IdentUser FindById(int userId)
    {
        return _dbContext.Users.Include(user => user.IdentUserProfile)
            .Include(role => role.IdentUserProfile.IdentUserOrgRole)
            .Include(client => client.IdentUserProfile.IdentMapApplicationsWithUser).FirstOrDefault(x => x.Id == userId);
    }

相反,我现在正在使用AspNetCore.Identity的FindByIdAsync

IdentUser User = await UserManager.FindByIdAsync(passwordObj.userId.ToString());

这解决了我的问题。不完全确定原因是什么,但直接使用DbContexts和异步调用看起来并不好。随意对任何解释发表评论