请参阅下面的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 包含有关传入请求、传出响应等信息。
尽管最简单的方法可能是通过在 web.config 中切换它来以ASP.Net 兼容模式运行服务。这应该使您可以访问 ASP.Net HttpContext。它会限制您使用 *HttpBindings 和 IIS 托管。要切换兼容模式,请将以下内容添加到 web.config。
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>