WCF Service中HttpContext.Current为null的解决办法

做了一个测试, 新建一个WebApplication项目, 分别添加 aspx page, asmx web service, WCF service(.svc), 针对每个请求的HttpContext.Current做观察, 结果如下:

  Item                HttpContext.Current                        HttpContext.Current.Session

aspx Page:                       Y                                                       Y

asmx web service              Y                                                           N

WCF service                      N                                                           N

 

针对上述结论, 在http://www.cnblogs.com/artech/archive/2009/06/24/1510497.html文章中[二、ASP.NET并行(Side by Side)模式]部分有提到, 在WCF寄宿在IIS的环境中, 当aspnet_isapi接收到client 的request之后,会被WCF 的处理程序直接截获,并不会执行aspx页面默认的执行管道, 因此在WCF hosting IIS的环境中是得到的HttpContext.Current永远是null的.

 

那我们有没有办法使在WCF hosting IIS的环境中使HttpContext.Current不为NULL, 能为我们所用呢?

经过测试发现只要注意下面亮点就可以了:

1. 在hosting WCF的web.config中加入:

<system.serviceModel>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

 

2. 在每个Service的定义(注意不是Contract, 不过就算加在Contract上编译是也会报错)上加上下面Attribute:

[AspNetCompatibilityrequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

 

再测试看看, 发现WCF hosting IIS的程序中也可以使用HttpContext.Current了.

 

PS:

NHibernate WCF中Session的问题其实也就可以解决了

 

 

posted @ 2010-01-07 13:57  DukeCheng  阅读(4395)  评论(3编辑  收藏  举报