HttpContext in a Task

By | December 15, 2014

At work recently, I needed to be able to get access to the HttpContext.Current value, as it contains the user currently on the site, as well as many other values that may be needed.  In my case, I needed both the user name, and the Url that the request came from, and I was coding in a service, where I didn’t have direct access to the ApiController methods.  However, most of our Api calls are done using async/await, so Task.Run comes in to play a lot.  The problem with HttpContext.Current is that the Response property hanging off of this value is null from within the Task; only the main thread has direct access to this information (as least, as far as I could research).

It turns out that there is a Synchronization context that you can use to get back on the main thread when your task has completed running.  It’s accessible through the TaskScheduler static class.  You ask for the current scheduler by calling the static FromCurrentSynchronizationContext method, which will return you a TaskScheduler intance that you can use for synchronizing your thread.

Now, if I want to log which user performed an action, for instance, I can get access to everything that’s on the HttpContext object.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.