tags:

views:

39

answers:

3

I've always wondered how you can access the correct state of the current http context via a static method:

HttpContext.Current.Session["foo"] = "bar";

In any other program, anywhere else, my initial assumption about working with a static accessor like this is that changing it will change it across all threads. Similarly, another thread running my change it on me while I am trying to use it.

But HttpContext.Current does not behave like this. It provides the appropriate state for the given request, even through the static accessor. How is this?

+1  A: 

Hey,

Well, it's wrapping the underlying request and pipeline objects; static objects do retain themselves across postbacks (across all requests), a painful lesson I had to learn... but anyway, objects do not get retained, but static objects that expose the underlying services and pipelines can work OK.

What I mean is that HttpContext.Current probably doesn't get preserved, because underneath, it is actually just exposes the available services within the .NET framework. These services may be unique to a request/user, as it would be up to the accessed service to determine that (session has something in-built to the service to make it unique to a user).

HTH.

Brian
+1  A: 

Basically, HttpContext has a static property getter named Current. In that property getter is code that determines the correct HttpContext object to return.** After that, you're using instance methods. Your snippet is equivalent to:

//Use a static property getter to get the correct HttpContext instance
HttpContext ctx = HttpContext.Current;

// Now use that instance
ctx.Session["foo"] = "bar";

Part of how it does it isn't really magic - the ASP.Net runtime sets HttpContext.Current for each request to a new instance of HttpContext. That setter stores the instance in thread static storage***. The getter then pulls the instance out of that storage for the current thread.

The key thing to note is that a static property or method isn't just global fields - it can use things like the current thread to alter what it does or what it returns.

**Actually, HttpContext.Current delegates to ContextBase, which delegates to CallContext, which ends up using methods on Thread, but the concept is the same.

***Actually, the runtime does a bit more to handle thread switching during a request.

Philip Rieck
A: 

HttpContext.Current is thread specific and therefore seems volatile (think of it like psuedo extension methods on the thread), Session is a static object associated to the application (or application thread). In short Context.Current will interogate the current thread.

AJ