I have an ASP.NET application targeting .NET 4.6, and am losing my mind trying to understand why HttpContext.Current becomes null after the first wait inside my async MVC controller action.
I checked and triple-checked that my project is targeting v4.6, and that the web.config attribute of targetFramework also 4.6.
SynchronizationContext.Current is assigned both before and after the wait, and it is correct, i.e. AspNetSynchronizationContext , not the former.
FWIW, the expected question switches the threads to continue, which is probably due to the fact that it calls an external input / output code (calling an asynchronous database), but this should not be a problem, AFAIU.
And yet, it is! The fact that HttpContext.Current getting null causes a number of problems for my code in line, and that makes no sense to me.
I checked the usual recommendations , and I am sure that I am doing everything I should. I also have absolutely no ConfigureAwait in my code!
What I have are several 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 user authorization and cleanup logic, which requires asynchronous. AFAIU, this is supported and should not be a problem.
What else could be causing this puzzling behavior that I see?
UPDATE: additional observation.
The SynchronizationContext link remains unchanged after waiting before and before waiting. But his internal changes change between them, as can be seen in the screenshots below!
BEFORE YOU WAIT: 
AFTER: 
I am not sure how (or even if) this may be relevant to my problem at the moment. Hope someone else can see it!