【发布时间】:2021-01-11 17:28:31
【问题描述】:
我有一个奇怪的情况,我不明白。在测试我的 API 时,我注意到缓慢的 api 查询归结为从商店中检索用户(登录后)。
当我在 UserStore 中覆盖 FindByIdAsync 方法时,我可以看到从 DbContext 中检索用户时有 500 毫秒的延迟。
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;
}
【问题讨论】:
标签: asp.net-mvc asp.net-core entity-framework-core asp.net-identity