为什么HttpContext.Current是静态的?

5
我有些困惑为什么HttpContext.Current是一个静态属性?如果运行时同时处理多个请求,那么所有请求不都会看到相同的Current值吗,因为它是静态的吗?还是由框架使用某些同步技术来处理,如果是这样,为什么不是普通属性呢?
有什么遗漏吗?
1个回答

8

这里是Current属性的实现:

public static HttpContext Current
{
  get
  {
    return ContextBase.Current as HttpContext;
  }
  set
  {
    ContextBase.Current = (object) value;
  }
}

还有在该属性中使用的ContextBase:

internal class ContextBase
{
  internal static object Current
  {
    get
    {
      return CallContext.HostContext;
    }
    [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] set
    {
      CallContext.HostContext = value;
    }
  }

以及 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;
      }
    }

CallContext.HostContext可以看出,它使用Thread.CurrentThread对象,并属于当前线程,因此不会与其他线程/请求共享。

有时您需要在Page\Controller以外访问HttpContext。例如,如果您有一些代码在其他地方执行,但是它是由Page触发的。那么在该代码中,您可以使用HttpContext.Current获取当前请求、响应和所有其他上下文数据。


1
@user3359453,这些代码片段是由微软在http://referencesource.microsoft.com上提供的,用于了解.NET框架的内部结构。 - Harsh Baid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接