I have an ASP.NET app targeting .NET 4.6 and I'm going crazy trying to figure out why HttpContext.Current
becomes null after the first await inside my async MVC controller action.
I've checked and triple-checked that my project is targeting v4.6 and that the web.config's targetFramework
attribute is 4.6 as well.
SynchronizationContext.Current
is assigned both before and after the await and it's the right one, i.e. AspNetSynchronizationContext
, not the legacy one.
FWIW, the await in question does switch threads on continuation, which is probably due to the fact that it invokes external I/O-bound code (an async database call) but that shouldn't be a problem, AFAIU.
And yet, it is! The fact that HttpContext.Current
becomes null causes a number of problems for my code down the line and it doesn't make any sense to me.
I've checked the usual recommendations and I'm positive I'm doing everything I should be. I also have absolutely no ConfigureAwait
's in my code!
What I DO have, is a couple of async event handlers on my HttpApplication
instance:
public MvcApplication()
{
var helper = new EventHandlerTaskAsyncHelper(Application_PreRequestHandlerExecuteAsync);
AddOnPreRequestHandlerExecuteAsync(helper.BeginEventHandler, helper.EndEventHandler);
helper = new EventHandlerTaskAsyncHelper(Application_PostRequestHandlerExecuteAsync);
AddOnPostRequestHandlerExecuteAsync(helper.BeginEventHandler, helper.EndEventHandler);
}
I need these two because of custom authorization & cleanup logic, which requires async. AFAIU, this is supported and shouldn't be a problem.
What else could possibly be the reason for this puzzling behavior that I'm seeing?
UPDATE: Additional observation.
The SynchronizationContext
reference stays the same after await vs. before await. But its internals change in between as can be seen in screenshots below!
I'm not sure how (or even if) this might be relevant to my problem at this point. Hopefully someone else can see it!