【问题标题】:Accessing the complete server path for a file in a WCF web service访问 WCF Web 服务中文件的完整服务器路径
【发布时间】:2011-09-18 15:46:03
【问题描述】:

我有一个带有 svc 文件的 Web 服务和一个使用 WCF 定义简单 Web 服务的代码隐藏。

显然我正在使用 svc 文件在服务器上托管 Web 服务。

我的服务需要访问 Web 服务所在的 Web 应用程序目录中的文件。

考虑以下结构:

Web application root folder: MyWebApp

MyWebApp (folder) -> Images (folder)

MyWebApp (folder) -> App_Code (folder)

MyWebApp (folder) -> WebServices (folder)

MyWebApp (folder) -> Data (folder)

MyWebApp (folder) -> Web.config (file)

MyWebApp (folder) -> WebServices (folder) -> MyWebService.svc (file)

MyWebApp (folder) -> App_Code (folder) -> MyWebService.cs (file)

MyWebApp (folder) -> Data (folder) -> myfile.txt

嗯。从 csharp 文件代码隐藏 Web 服务文件中,我想访问位于相应数据文件夹中的 xml 文件。

我该怎么做???我当然不能访问服务器对象...

谢谢

【问题讨论】:

    标签: asp.net wcf iis


    【解决方案1】:

    如果您在 IIS 中托管:

    var root = HostingEnvironment.ApplicationPhysicalPath;
    var someFile = Path.Combine(root, "images", "test.png");
    

    当然,话虽如此,您绝对不应该在 WCF 服务操作中编写此类代码。您应该让此服务将路径作为构造函数参数,然后简单地配置您的依赖注入框架以传递正确的值:

    public class MyService1: IMyService
    {
        private readonly string _path;
        public MyService1(string path)
        {
            _path = path;
        }
    
        public void SomeServiceOperation()
        {
            var someFile = Path.Combine(_path, "images", "test.png");
            // TODO: do something with the file
        }
    }
    

    现在剩下的就是写一个custom IInstanceProvider 来连接你的依赖注入框架。这样,您的服务代码不再依赖于托管服务的方式/位置。该服务只需要一个文件路径 => 将其注入其中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 2019-12-28
      相关资源
      最近更新 更多