2009-04-26 60 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 
相关问题