Asp.net 为什么HttpContext.Current是静态的?
我有点困惑为什么HttpContext.Current是一个静态属性?如果运行时同时处理1个以上的请求,所有请求是否都会看到相同的Current值,因为它是静态的?或者它是通过使用某种同步技术的框架工作来处理的,如果是这样,为什么静态属性不是正常属性呢Asp.net 为什么HttpContext.Current是静态的?,asp.net,Asp.net,我有点困惑为什么HttpContext.Current是一个静态属性?如果运行时同时处理1个以上的请求,所有请求是否都会看到相同的Current值,因为它是静态的?或者它是通过使用某种同步技术的框架工作来处理的,如果是这样,为什么静态属性不是正常属性呢 缺少什么?以下是当前属性的实现: public static HttpContext Current { get { return ContextBase.Current as HttpContext; } set {
缺少什么?以下是当前属性的实现:
public static HttpContext Current
{
get
{
return ContextBase.Current as HttpContext;
}
set
{
ContextBase.Current = (object) value;
}
}
internal class ContextBase
{
internal static object Current
{
get
{
return CallContext.HostContext;
}
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)] set
{
CallContext.HostContext = value;
}
}
以及在该属性中使用的ContextBase:
public static HttpContext Current
{
get
{
return ContextBase.Current as HttpContext;
}
set
{
ContextBase.Current = (object) value;
}
}
internal class ContextBase
{
internal static object Current
{
get
{
return CallContext.HostContext;
}
[SecurityPermission(SecurityAction.Demand, Unrestricted = true)] set
{
CallContext.HostContext = value;
}
}
和调用上下文:
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。例如,若您有一些代码在其他地方执行,但它是从页面触发的。然后,在该代码中,您可以使用
HttpContext.Current
从当前请求、响应和所有其他上下文数据中获取数据。@user3359453供参考。这些代码位由microsoft在提供,用于理解.NET framework的内部结构