title: ASP.NET 4.6 async controller method loses HttpContext.Current after await
body: <p>I have an ASP.NET app targeting .NET 4.6 and I'm going crazy trying to figure out why <code>HttpContext.Current</code> becomes null after the first await inside my async MVC controller action.</p>
  
  <p>I've checked and triple-checked that my project is targeting v4.6 and that the web.config's <code>targetFramework</code> attribute is 4.6 as well.</p>
  
  <p><code>SynchronizationContext.Current</code> is assigned both before and after the await and it's the right one, i.e. <code>AspNetSynchronizationContext</code>, not the legacy one.</p>
  
  <p>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.</p>
  
  <p>And yet, it is! The fact that <code>HttpContext.Current</code> becomes null causes a number of problems for my code down the line and it doesn't make any sense to me.</p>
  
  <p>I've checked <a href="https://stackoverflow.com/questions/18383923/why-is-httpcontext-current-null-after-await">the usual recommendations</a> and I'm positive I'm doing everything I should be. I also have absolutely no <code>ConfigureAwait</code>'s in my code!</p>
  
  <p>What I DO have, is a couple of async event handlers on my <code>HttpApplication</code> instance:</p>
  
  <pre><code>public MvcApplication()
  {
      var helper = new EventHandlerTaskAsyncHelper(Application_PreRequestHandlerExecuteAsync);
      AddOnPreRequestHandlerExecuteAsync(helper.BeginEventHandler, helper.EndEventHandler);
  
      helper = new EventHandlerTaskAsyncHelper(Application_PostRequestHandlerExecuteAsync);
      AddOnPostRequestHandlerExecuteAsync(helper.BeginEventHandler, helper.EndEventHandler);
  }
  </code></pre>
  
  <p>I need these two because of custom authorization &amp; cleanup logic, which requires async. AFAIU, this is supported and shouldn't be a problem.</p>
  
  <p>What else could possibly be the reason for this puzzling behavior that I'm seeing?</p>
  
  <p><strong>UPDATE: Additional observation.</strong></p>
  
  <p>The <code>SynchronizationContext</code> reference stays the same after await vs. before await. But its internals change in between as can be seen in screenshots below!</p>
  
  <p><strong>BEFORE AWAIT:</strong>
  <a href="https://i.stack.imgur.com/4KB53.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4KB53.png" alt="Before entering await"></a></p>
  
  <p><strong>AFTER AWAIT:</strong>
  <a href="https://i.stack.imgur.com/8PV65.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8PV65.png" alt="After continuing"></a></p>
  
  <p>I'm not sure how (or even if) this might be relevant to my problem at this point. Hopefully someone else can see it!</p>