How does HttpContext.Current work?
This is kind of a hard question to formulate. I'm wondering how HttpContext.Current gets assigned a unique instance for every request considering 开发者_开发百科it's a static object?
Thanks!
Current is not a static variable, its static property, and get property is nothing but a static method which returns the current Context.
ASP.NET stores some information with current thread, you can always get a local thread storage to store information which is kind of static only in the current thread, and which can be accessible by any method in current thread only.
So ASP.NET stores some local information in the thread in which the http context executes the requested application and from anywhere call to Current will fetch the local thread data and get required information.
You can also look at [ThreadStatic]
attribute which does things almost in similar way.
Update
From ASP.NET 4.5 and after, Current HttpContext
is passed through CallContext
instead of [ThreadStatic]
, so context remains available through out async calls in single logical context instead of current thread as each async call may end up on different threads.
You should read this blog post:
http://odetocode.com/Articles/112.aspx
The section that starts with the following should be of interest to you. It's long or else I would quote more of it:
The curious among us will wonder just how HttpContext.Current can find the context for the current request.
精彩评论