请参阅下面的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