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!
HttpContext is an object that wraps all http related information into one place. HttpContext. Current is a context that has been created during the active request. Here is the list of some data that you can obtain from it.
ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.
HTTP context accessor. Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With