我想要获取 WCF 应用程序的工作文件夹。我怎么才能得到它?

如果我尝试

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

我收到空引用异常(Http.Current 对象为空)。


我所说的工作文件夹是指运行 WCF 服务的文件夹。如果我设置 aspNetCompatibilityEnabled="true", ,我收到此错误:

服务器没有提供有意义的回复;这可能是由合同不匹配、会话过早关闭或内部服务器错误引起的。

有帮助吗?

解决方案

我需要为我的IIS6相同的信息承载的WCF应用程序,我发现这个工作对我来说:

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

和往常一样,因人而异。

其他提示

请看下面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 服务可以通过多种不同的方式并使用不同的端点来托管,因此工作文件夹稍微不明确。

您可以通过调用来检索正常的“工作文件夹” 目录.GetCurrentDirectory().

HttpContext 是一个 ASP.Net 对象。即使 WCF 可以托管在 IIS 上,它仍然不是 ASP.Net,因此大多数 ASP.Net 技术在默认情况下都不起作用。OperationContext 相当于 WCF 中的 HttpContext。OperationContext 包含有关传入请求、传出响应等的信息。

虽然最简单的方法可能是运行该服务 ASP.Net 兼容模式 通过在 web.config 中切换它。这将使您能够访问 ASP.Net HttpContext。但它会限制您只能使用 *HttpBindings 和 IIS 托管。要切换兼容模式,请将以下内容添加到 web.config 中。

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
</system.serviceModel>

根据你想要什么。我通常要解决像“〜/文件夹/文件”的URL。这是什么工作。

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

更一般的,我使用的这一个

AppDomain.CurrentDomain.BaseDirectory

在aspNetCompatibilityEnabled =“真实”应该已经解决了我的问题,但我得到这个错误:

  

服务器没有提供有意义的答复;这可能是由合同不匹配,会话提前关闭或内部服务器错误引起的。

我解决我的问题,从我目前的应用领域得到它让我跑WCF服务的物理路径:

AppDomain.CurrentDomain.BaseDirectory

为了引用ASP.NET功能,如HttpContext对象,你需要运行在ASP.NET兼容模式下您的WCF应用程序。这文章解释如何做到这一点。

使用HostingEnvironment.ApplicationPhysicalPath WCF中找到您的应用程序的物理路径。 使用命名空间 使用System.Web.Hosting;

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top