Fork me on GitHub

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

    今天做WCF的时候,需要读取服务器上的一个文本文件,但是用WCF始终获取不到HttpContext。不是我不想去学习原理,实在是时间不够充裕,找到一篇很好的文章,所以就转帖了。

 

做了一个测试, 新建一个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了.

 

转至:http://www.cnblogs.com/Flyear/archive/2010/01/07/1641199.html

 

posted @ 2010-05-07 14:42  idoku  阅读(711)  评论(0编辑  收藏  举报