Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 445
Micah Avatar asked Aug 05 '10 16:08

Micah


People also ask

What does HttpContext current do?

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.

How use HttpContext current in .NET Core?

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.

How do I find HttpContext current?

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.

What is HttpContext system?

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.


1 Answers

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.

like image 131
Akash Kava Avatar answered Sep 18 '22 12:09

Akash Kava