[转]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
作 者:doku
出 处:http://www.cnblogs.com/kulong995/
关于作者:喜欢编程,喜欢美食,专注于.NET项目开发。
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是作者坚持原创和持续写作的最大动力!