如果我尝试:
HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath)
我遇到了空引用异常(Http.Current对象为空)。
我所说的“工作目录”是我的WCF服务运行的文件夹。如果我设置aspNetCompatibilityEnabled="true"
,则会出现以下错误:
服务器没有提供有意义的回复;这可能是由于合同不匹配、过早的会话关闭或内部服务器错误引起的。
HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath)
我遇到了空引用异常(Http.Current对象为空)。
我所说的“工作目录”是我的WCF服务运行的文件夹。如果我设置aspNetCompatibilityEnabled="true"
,则会出现以下错误:
服务器没有提供有意义的回复;这可能是由于合同不匹配、过早的会话关闭或内部服务器错误引起的。
我需要在我的IIS6托管的WCF应用程序中获取相同的信息,我发现这对我有用:
string apPath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
像往常一样,结果可能因人而异。
请查看下面ongle的回答,它比这个更好。
在获取更多信息后更新
以下内容对我有效。我测试了一个新的WCF服务,通过Service1.svc托管在IIS上。
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
添加到web.config中。<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>
string path = HttpContext.Current != null
? HttpContext.Current.Server.MapPath("~/folder/file")
: System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "folder", "file");
- Simon_Weaver根据你的需求而定。我通常想要解析一个像"~/folder/file"这样的url。以下是解决方法。
System.Web.Hosting.HostingEnvironment.MapPath("~/folder/file");
更普遍地说,我正在使用这一个
AppDomain.CurrentDomain.BaseDirectory
虽然aspNetCompatibilityEnabled="true"应该解决了我的问题,但我遇到了以下错误:
服务器没有提供有意义的回复;这可能是由于合同不匹配、会话过早关闭或内部服务器错误引起的。
通过从当前应用程序域获取运行中WCF服务的物理路径来解决了我的问题:
AppDomain.CurrentDomain.BaseDirectory
在WCF中使用HostingEnvironment.ApplicationPhysicalPath来查找应用程序的物理路径。 使用命名空间 using System.Web.Hosting;