-1

我想使用AspNetCore.Identity程序集實現密碼重置機制。它從用戶開始說他們忘記了密碼,輸入他們的電子郵件和密碼,然後提交。最後調用此代碼AspNetCore.Identity重置密碼 - 「X」的實例無法跟蹤

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); 

我沒有任何問題生成一個重置密碼令牌,任務運行完成,我得到一個電子郵件與正確的URL。

然而,當我嘗試重置密碼,我得到這個塊的代碼

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線產生一個異常說「實體類型‘IdentUser’的實例無法被追蹤因爲另一個這種類型的相同鍵的實例已被跟蹤

我還是比較新的ASP.NET核心,我剛開始學習異步調用的來龍去脈,所以我有一個艱難的時間調試這個。我已經搜索了答案,沒有發現任何解決我的問題的東西,所以我就在這裏。有關如何解決或調試此問題的任何想法?

+1

可能是不相關的,但是你最好不要等待異步調用? –

回答

0

所以,我想出了我的問題,併發布我的修復程序,希望可以幫助其他人面對此問題。

我的FindById函數是在AspNetCore.Identity的UserManager的擴展中實現的,IdentUserManager。 FindById是不是異步 - >

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並且異步調用似乎不能很好地混合。隨意與任何解釋發表評論

相關問題