Asp.NetCore UserStore减缓了用户从数据库上下文中检索的速度



我有一个奇怪的情况,我不明白。在测试我的API时,我注意到了缓慢的API查询,这归结为从存储中检索用户(登录后(。

当我在UserStore中重写FindByIdAsync方法时,我可以看到从DbContext检索用户时延迟了500ms。

public override async Task<User> FindByIdAsync(string userId, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
if (!int.TryParse(userId, out int id))
{
return null;
}
// This takes 500+ ms
return Context.User.FirstOrDefault(u => u.Id == id);
}

现在奇怪的是,当我在控制器中做同样的事情时,速度很快。

例如:

[HttpGet]
public async Task<IActionResult> Get()
{
// This function will end up at the UserStore.FindByIdAsync (see above)
// And takes 500+ ms
User user = await signInManager.UserManager.GetUserAsync(this.User);
// This however is fast... (just using a sample id)
context.User.Where(u => u.Id == 1896);
return Ok(await context.Session.Where(s => s.UserId == user.Id).ToListAsync());
}

我不明白为什么。我试着交换这两个函数,看看这是热身还是什么。但事实并非如此。。

我还查看了UserStore和Context中的源代码,其中应该与Controller 中的上下文相同

我在控制器中注入上下文:

public SessionController(SignInManager<User> signInManager, MyDbContext context)
{
this.signInManager = signInManager;
// This is the same context as in the UserStore since the context is also injected in the  UserStore
this.context = context;
}

在等待调用时添加ConfigureAwait(false(User User=等待signInManager。UserManager。GetUserAsync(this.User(.ConfigureAwait(false(;等待上下文。一场其中(s=>s.UserId==user.Id(.ToListAsync((.ConfigureAwait(false(

最新更新