![](/img/trans.png)
[英]Updating user by UserManager.Update() in ASP.NET Identity 2
[英].Net Core 1 Identity UserManager cached user list not updating
環境:.Net Core 1,EF,使用Identity進行身份驗證,使用JWT令牌進行授權。
遇到使用UserManager.ChangePasswordAsync()
方法的問題是正確更新數據庫,但是沒有更新UserManager.Users
列表(假設)。
在Startup.cs中,我們只是使用app.UseIdentity()
,而在ApplicationUserService
構造函數中,我們正在注入UserManager<ApplicationUser>
。 除此之外,我們沒有做任何習慣。
例如:假設用戶將其密碼從“password1”更改為“password2”。 如果該用戶注銷並重新登錄,則UserManager仍認為密碼為“password1”。 如果我重新啟動WebAPI服務器,則嘗試登錄; 它可以像你期望的那樣使用“password2”。 所以它肯定會更新數據庫,但UserManager的范圍/緩存沒有更新。
我想知道UserManager的默認DI范圍是否是單例(而不是每個請求)? 如果它沒有更新UserStore的緩存用戶列表,我可以看到導致此問題。
有什么建議么? 需要更多代碼?
ApplicationUserService(簡化):
private readonly UserManager<ApplicationUser> _userManager;
public ApplicationUserService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public Task<IdentityResult> ChangePasswordAsync(ApplicationUser user, string currentPassword, string newPassword)
{
return _userManager.ChangePasswordAsync(user, currentPassword, newPassword);
}
[編輯]
我不確定為什么會出現這種情況,但我剛才意識到,如果我將UserManager和SignInManager直接注入到Controller的構造函數中(而不是注入Service層),它似乎工作得很好。
[編輯2]
調查結果摘要:
1)將UserManager和SignInManager注入到Service構造函數中,然后將該Service注入Controller構造函數不起作用。
2)將UserManager和SignInManager注入Controller構造函數。
3)我還在Controller構造函數中測試了IServiceProvider的使用。 我注入了IServiceProvider,然后使用GetService方法設置管理器: _userManager = serviceProvider.GetService<UserManager<ApplicationUser>>();
。 這與#1的結果相同。
在#1和#3中:它將保存到數據庫,但管理員似乎在以后使用時不知道數據更改。 在這兩種情況下,我都必須重新初始化應用程序(停止並啟動服務器),以便更新緩存的數據。
不應該#3和#2一樣工作嗎?
[注意:以下代碼不適用於Asp.Net Core。 有關Asp.Net Core中的身份驗證,請查看此文檔 。]
我是Asp.Net的新手,但我嘗試制作你所描述的內容。 對我而言,它按預期工作。 也許我的代碼可以為你激發一個想法。
internal static void Main(string[] args)
{
_userStore = new UserStore<ApplicationUser>(new IdentityDbContext<ApplicationUser>());
_userManager = new UserManager<ApplicationUser>(_userStore);
var x = new ApplicationUser();
x.UserName = "Test";
foreach(string error in _userManager.Create(x, "password").Errors)
{
Console.WriteLine(error);
}
Console.WriteLine(_userManager.CheckPassword(x, "password"));
var f = ChangePasswordAsync(x, "password", "pass12345");
f.ContinueWith(delegate
{
if (f.IsFaulted)
{
Console.WriteLine(f.Exception.Message);
}
}).ContinueWith(delegate
{
Console.WriteLine(_userManager.CheckPassword(x, "password"));
});
Console.ReadKey(true);
}
private static UserStore<ApplicationUser> _userStore;
public class ApplicationUser : IdentityUser { }
private static UserManager<ApplicationUser> _userManager;
public static Task<IdentityResult> ChangePasswordAsync(ApplicationUser user, string currentPassword, string newPassword)
{
return _userManager.ChangePasswordAsync(user.Id, currentPassword, newPassword);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.