2009-04-26 36 views
66

我想獲取WCF應用程序的工作文件夾。我怎麼才能得到它?如何獲得wcf應用程序的工作路徑?

如果我嘗試

HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath) 

我得到一個空引用異常(該Http.Current對象爲null)。


我的工作文件夾的含義是我的WCF服務運行的文件夾。如果我設置aspNetCompatibilityEnabled="true",我得到這個錯誤:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

回答

164

我需要爲我的IIS6相同的信息承載的WCF應用程序,我發現這個工作對我來說:

string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath; 

一如既往,YMMV。

3

爲了引用ASP.NET功能,如HttpContext對象,你需要運行在ASP.NET兼容模式下您的WCF應用程序。這article解釋瞭如何做到這一點。

31

請參閱下面的ongle的答案。它比這個好得多。

更多信息

以下爲我工作後更新。我通過Service1.svc在IIS上託管的新WCF服務對其進行了測試。

  1. <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>添加到網絡配置。 <system.serviceModel>..</ ..>已經存在。
  2. AspNetCompatibilityRequirementsAttribute添加到模式允許的服務。
  3. 使用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> 
+0

我的「工作文件夾」的意思是在我的WCF服務正在運行的物理路徑。我有一個XML文件,我想讀它。 Directory.GetCurrentDirectory()不起作用,當我嘗試設置你說的兼容模式時,我得到這個錯誤: 服務器沒有提供有意義的回覆;這可能是由於合同不匹配,會話過早關閉或內部服務器錯誤造成的。 – 2009-04-26 20:11:01

+0

使用經過測試的示例代碼更新了答案。 – 2009-04-26 20:58:31

+9

使用這與ASPNET上下文或沒有System.Web.Hosting.HostingEnvironment.MapPath(「〜/文件夾/文件」); – 2010-04-02 05:09:35

12

的aspNetCompatibilityEnabled =「真實」應該已經解決了我的問題,但我得到這個錯誤:

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

我解決我的問題,從得到它讓我跑WCF服務的物理路徑我目前的應用程序域:

AppDomain.CurrentDomain.BaseDirectory 
20

取決於你想要什麼。我通常想解析一個像「〜/文件夾/文件」的網址。這是有效的。

System.Web.Hosting.HostingEnvironment.MapPath("~/folder/file"); 
2

在WCF中使用HostingEnvironment.ApplicationPhysicalPath來查找您的應用程序物理路徑。 使用命名空間 using System.Web.Hosting;

15

比較一般,我用這一個

AppDomain.CurrentDomain.BaseDirectory 
相關問題