Question

I have an MVC 4.0 site which is using the BCL async/await package. To preserve HttpContext across the initial thread and the subsequent thread (after the await) I began by creating a closure with a reference to the context like so:

   public async Task<ViewResult> GetCustomer(int id)
      {            
       var ctx =  HttpContext.Current;
       ctx["test"] = "test";

       await DoSomeLongRunningIO();

       var test = ctx["test"];
       //do other things with context

       return View();
    }

However, I need to call various services after the await. These legacy services call the HttpContext.Current directly. So I approached this with the following code, which seemed like a simple way to ensure these services still work as expected.

  public async Task<ViewResult> GetCustomer(int id)
      {            
       var ctx =  HttpContext.Current;

       await DoSomeLongRunningIO();

       HttpContext.Current = ctx;

       //call other services which use static references to httpcontext
       return View();
    }

This does work, however I have been reading this answer that suggests it is a bad idea:

  1. Is this a bad idea, and if so why is it worse than the first example?

Thanks for your time.

Was it helpful?

Solution

Are you aware that async/await in an ASP.NET app on .NET 4.0 is undefined?

If you upgrade to .NET 4.5, you'll find that HttpContext is preserved automatically for you. There's no need for closures or to set it.

Setting HttpContext.Current is a bad idea, because you're bypassing the ASP.NET safety checks that ensure there is only one thread at a time with that context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top