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.rzrgm.cn/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的問題其實也就可以解決了
浙公網安備 33010602011771號