0
在生成JWT令牌時,我遇到了一個持續性問題,大約有30%的情況。UserManager asp.net Core 2.0:連接未關閉。 '正在連接'
原來的設置是使用依賴注入,但對錯誤的發現,我的UserManager實例在下面的代碼「新鮮」:
[AllowAnonymous]
[Route("token")]
public async Task<BaseResult> Token(string email, string password)
{
if (email == null) return new BaseResult(BaseResult.ResultCodes.InvalidInput, "not a user");
//var user = await UserManager.FindByNameAsync(email);
using (UserManager<User> usermanager = new UserManager<User>(new UserStore<User>(new UserContext()), null,
new PasswordHasher<User>(), null, null, null, null, null, null))
{
User user = await usermanager.FindByEmailAsync(email);
if (user == null)
return new BaseResult(BaseResult.ResultCodes.NotFound, "user not found");
if (usermanager.PasswordHasher.VerifyHashedPassword(user, user.PasswordHash, password) !=
PasswordVerificationResult.Success)
return new BaseResult(BaseResult.ResultCodes.InvalidInput, "password incorrect");
var token = await GetJwtSecurityToken(user);
return new TokenResult(new JwtSecurityTokenHandler().WriteToken(token), token.ValidTo);
}
//{
// token = new JwtSecurityTokenHandler().WriteToken(token),
// expiration = token.ValidTo
//});
}
異常大幹快上usermanager.FindByEmailAsync(電子郵件)的30%拋出案例和內容如下:
System.InvalidOperationException:'連接未關閉。連接的當前狀態正在連接。「
由於在上面的行中創建了上下文,所以這個錯誤我不明白。考慮到SQL服務器沒有完全從先前的請求中完成,儘管它在新開始時經常發生。
信息目的:我的背景:
public sealed class UserContext:IdentityDbContext<User>
{
public UserContext()
{
Database.EnsureCreatedAsync();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer($"Server =PC; Database =PFUsers; Trusted_Connection = True;MultipleActiveResultSets=true;");
base.OnConfiguring(optionsBuilder);
}
}
雖然進行調試規避,但使用DI時,相關啓動部是:
services.AddEntityFrameworkSqlServer()
.AddDbContext<UserContext>(ServiceLifetime.Scoped);
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<UserContext>();