HttpContext.Current为NULL

  • 总结:HttpContext.Current是基于System.Runtime.Remoting.Messaging.CallContext这个类,子线程和异步线程都无法访问到主线程在CallContext中保存的数据。所以在异步执行的过程会就会出现HttpContext.Current为null的情况。
  • 详解

CallContext 是类似于方法调用的线程本地存储区的专用集合对象,并提供对每个逻辑执行线程都唯一的数据槽。 数据槽不在其他逻辑线程上的调用上下文之间共享。 当 CallContext 沿执行代码路径往返传播并且由该路径中的各个对象检查时,可将对象添加到其中。

当对另一个 AppDomain 中的对象进行远程方法调用时,CallContext 类将生成一个与该远程调用一起传播的 LogicalCallContext 实例。 只有公开ILogicalThreadAffinative 接口并存储在 CallContext 中的对象被在 LogicalCallContext 中传播到 AppDomain 外部。 不支持此接口的对象不在LogicalCallContext 实例中与远程方法调用一起传输。

  • 解决:在异步前面就把HttpContext.Current用HttpContext的方式存起来,然后能过参数的形式传递进去。

1.建立一个属性:

public HttpContext context 
{ 
get { return HttpContext.Current; } 
set { value = context; } 
} 

  

2.建立一个委托:

public delegate string delegategetResult(HttpContext context); 

  

3.使用的核心代码:

context = HttpContext.Current; 
delegategetResult dgt = testAsync; 
IAsyncResult iar = dgt.BeginInvoke(context, null, null); 
string result = dgt.EndInvoke(iar); 

  

原文地址:https://www.cnblogs.com/jiaoxh/p/5431208.html