Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Identity canceled when using FindByIdAsync

I'm have a small project that uses the Asp.Net Core Identity framework together with EF Core. One function calls the UserManager.FindByIdAsync(id) and it returns the proper object. However, it only works a few minutes after the application is started. As long as the server is busy it works fine, but as soon as the application is idle more than 1-2 minutes the request fails.

It fails with:

*OperationCanceledException: The operation was canceled.
System.Threading.CancellationToken.ThrowOperationCanceledException()*

The stacktrace looks like this:

*System.Threading.CancellationToken.ThrowOperationCanceledException()
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore.FindByIdAsync(string userId, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId)
MyProject.Areas.Admin.ControllerServices.UserService+<GetUser>d__11.MoveNext() in UserService.cs*

I'm still logged in as other pages are working fine. A simple call to the EF context.Users.FindAsync(new object[] { id }) will work as expected, but the next line containing FindByIdAsync will fail.

All this works perfect in the dev environment, the error occurs when the application is installed on the server running IIS on WS 2008 R2. Recycling the app pool will make it work again until it is idle again for a few minutes.

I have noted that when lines like 'Connection id "0HL5E91K33IIQ" reset.' are being logged, then the app starts to fail. Prior to that it works.

FindByIdAsync is not the only identity function to fail, many other functions fails with the same error.

What am I missing?

like image 365
mke08 Avatar asked Jun 08 '17 08:06

mke08


1 Answers

I will answer my own question, and hopefully this will help someone else in the future.

For me, it all boiled down to the lifetime of the injected services. UserManager depends on IHttpContextAccessor (this is where the CancellationToken comes from) and it behaves incorrectly when lifetimes do not match up. IHttpContextAccessor is added as a Singleton service, while the UserManager is added as a scoped service. My service that used the UserManager was added as a Singleton service. Changing this to Scoped made the errors go away.

like image 122
mke08 Avatar answered Sep 22 '22 11:09

mke08