請參閱下面的ongle的答案。它比這個好得多。
更多信息
以下爲我工作後更新。我通過Service1.svc在IIS上託管的新WCF服務對其進行了測試。
- 將
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
添加到網絡配置。 <system.serviceModel>..</ ..>
已經存在。
- 將
AspNetCompatibilityRequirementsAttribute
添加到模式允許的服務。
- 使用
HttpContext.Current.Server.MapPath(".");
獲取根目錄。
以下是服務類的完整代碼。我沒有改變IService1接口。
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public void DoWork()
{
HttpContext.Current.Server.MapPath(".");
}
}
下面是摘自web.config的內容。
<system.serviceModel>
<!-- Added only the one line below -->
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
<!-- Everything else was left intact -->
<behaviors>
<!-- ... -->
</behaviors>
<services>
<!-- ... -->
</services>
</system.serviceModel>
老答案
你說的工作文件夾是什麼意思? WCF服務可以以幾種不同的方式承載,並且具有不同的端點,所以工作文件夾稍微不明確。
您可以檢索正常的「工作文件夾」,具有Directory.GetCurrentDirectory()通話。
HttpContext是一個ASP.Net對象。即使WCF可以在IIS託管,它仍然不是ASP.Net因爲這個原因,大多數的ASP.Net技術,默認情況下不工作。 OperationContext是WCF的HttpContext的等價物。 OperationContext包含關於傳入請求的信息,傳出響應等等。
雖然最簡單的方法可能是通過ASP.Net compatibility mode在web.config中切換它來運行服務。這應該讓你訪問ASP.Net HttpContext。它會限制你到* HttpBindings和IIS託管。要切換兼容模式,請將以下內容添加到web.config中。
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
我的「工作文件夾」的意思是在我的WCF服務正在運行的物理路徑。我有一個XML文件,我想讀它。 Directory.GetCurrentDirectory()不起作用,當我嘗試設置你說的兼容模式時,我得到這個錯誤: 服務器沒有提供有意義的回覆;這可能是由於合同不匹配,會話過早關閉或內部服務器錯誤造成的。 – 2009-04-26 20:11:01
使用經過測試的示例代碼更新了答案。 – 2009-04-26 20:58:31
使用這與ASPNET上下文或沒有System.Web.Hosting.HostingEnvironment.MapPath(「〜/文件夾/文件」); – 2010-04-02 05:09:35