【问题标题】:How Can I Find The Path To A Folder from a Controller Constructor in ASP.NET MVC?如何从 ASP.NET MVC 中的控制器构造函数中找到文件夹的路径?
【发布时间】:2009-01-22 02:23:13
【问题描述】:

我正在尝试获取网站根目录中文件夹的路径,并在调用控制器构造函数时将其保存到类属性中:

public TestController:Controller{
    string temp;

    public TestController(){
        temp = "";
        }

    }

我尝试了以下方法:

temp = Server.MapPath("~/TheFolder/"); // Server is null - error.
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error.

有什么想法吗?

【问题讨论】:

    标签: .net asp.net-mvc


    【解决方案1】:

    AppDomain.CurrentDomain.BaseDirectory 将为您提供网站的根目录。所以:

    temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder");
    

    (感谢 Marc Gravell 的评论更新)

    【讨论】:

    • Path.Combine 会更好 ;-p
    • 这将返回临时文件夹目录,这可能意味着完全错误的文件夹。
    【解决方案2】:

    在构造过程中你真的需要这条路径吗?如果您在主页周期开始之前不需要它,请考虑推迟它 - 只需使用常规属性;像

    public string BasePath {
        get { return Server.MapPath("~/TheFolder/"); }
    }
    

    那么当在页面循环中使用这个时,应该没问题。如果你真的想缓存它,你可以缓存它,但我不认为这会成为瓶颈:

    private string basePath;
    public string BasePath {
        get {
            if(basePath == null) basePath = Server.MapPath("~/TheFolder/");
            return basePath;
        }
    }
    

    【讨论】:

    • 这是个好主意。我以后可能会走这条路。谢谢!
    【解决方案3】:

    尝试通过 ControllerContext。请原谅我的语法,但它应该是这样的:

    base.[Controller?]Context.HttpContext.Server.MapPath();
    

    如果 Server 在这种情况下仍然为空,您是否在 Web 请求之外运行(即在测试中)?

    【讨论】:

      猜你喜欢
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      相关资源
      最近更新 更多