user3359453
user3359453

Reputation: 359

Why HttpContext.Current is Static?

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 ?

Upvotes: 5

Views: 762

Answers (1)

Sergey Litvinov
Sergey Litvinov

Reputation: 7458

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.

Upvotes: 8

Related Questions