I am a bit confused why HttpContext.Current is a static property ? If runtime is processing more than 1 requests at the time, will not all the requests see the same value of Current ,since it is static ? or it is handled by frameworking using some synchronization technique and if it is so, why static not normal property.
Missing something ?
Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
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.
The HttpContext is NOT thread safe, accessing it from multiple threads can result in exceptions, data corruption and generally unpredictable results.
HttpRequest is a subset of HttpContext . In other words, the HttpContext includes the response, the request, and various other data that's not relevant to a specific request or response; such as the web application, cached data, server settings and variables, session state, the authenticated user, etc.
Here is implementation of Current
property:
public static HttpContext Current
{
get
{
return ContextBase.Current as HttpContext;
}
set
{
ContextBase.Current = (object) value;
}
}
And ContextBase that used in that property:
internal class ContextBase
{
internal static object Current
{
get
{
return CallContext.HostContext;
}
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)] set
{
CallContext.HostContext = value;
}
}
And CallContext:
public sealed class CallContext
{
public static object HostContext
{
[SecurityCritical]
get
{
ExecutionContext.Reader executionContextReader =
Thread.CurrentThread.GetExecutionContextReader();
return executionContextReader.IllogicalCallContext.HostContext ?? executionContextReader.LogicalCallContext.HostContext;
}
[SecurityCritical]
set
{
ExecutionContext executionContext =
Thread.CurrentThread.GetMutableExecutionContext();
if (value is ILogicalThreadAffinative)
{
executionContext.IllogicalCallContext.HostContext = (object) null;
executionContext.LogicalCallContext.HostContext = value;
}
else
{
executionContext.IllogicalCallContext.HostContext = value;
executionContext.LogicalCallContext.HostContext = (object) null;
}
}
As you can see from the CallContext.HostContext
it uses Thread.CurrentThread
object, and it belongs to current thread, so it won't be shared with others threads\requests.
Sometimes you need to have access to HttpContext outside from Page\Controller. For example if you have some code that executes somewhere else, but it was triggered from Page. Then in that code you can use HttpContext.Current
to get data from current request, response and all other context data.
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