title: Using HttpContext in Async Task
body: <p>I have the following mvc action.</p>
  
  <pre><code>public async Task&lt;JsonResult&gt; DoSomeLongRunningOperation()
  {
      return await Task.Run(() =&gt;
      {
          //Do a lot of long running stuff
          //The underlying framework uses the HttpContext.Current.User.Identity.Name so the user is passed on the messagebus.
      }
  }
  </code></pre>
  
  <p>In the task the HttpContext gets null. We did a lot of tricking, but nothing assures us of the HttpContext being available always in our new thread.</p>
  
  <p>Is there a solution to use HttpContext within out async tasks?</p>
  
  <p>In our IocContainer we have registered the following object which passes the username to the framework.</p>
  
  <pre><code>public class HttpContextUserIdentityName : ICredentials
  {
      public string Name
      {
          get { return HttpContext.Current.User.Identity.Name; }
      }
  }
  </code></pre>
  
  <p>This code is called in a lot of places before persisting to the database.</p>
  
  <p>We need either another way of getting the username of the user initiated the webrequest or fix the issue with the HttpContext being null.</p>
  
  <p>Because the persisting to the database happens in the Task I can't access the HttpContext before entering the task.</p>
  
  <p>I also can't think of a safe way to temporary persist the username so I can implement another ICredentials service object.</p>