如何從ASP.NET MVC中的Controller構造函數中找到文件夾的路徑?

[英]How Can I Find The Path To A Folder from a Controller Constructor in ASP.NET MVC?


I am trying to get the path to a folder in my website root and save it to a class property when my controller constructor is called:

我試圖獲取我的網站根目錄中的文件夾的路徑,並在調用我的控制器構造函數時將其保存到類屬性:

public TestController:Controller{
    string temp;

    public TestController(){
        temp = "";
        }

    }

I have tried the following:

我嘗試過以下方法:

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

Any ideas?

有任何想法嗎?

3 个解决方案

#1


25  

AppDomain.CurrentDomain.BaseDirectory will give you the root of your site. So:

AppDomain.CurrentDomain.BaseDirectory將為您提供站點的根目錄。所以:

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

(Update thanks to Marc Gravell's comment)

(感謝Marc Gravell的評論)

#2


7  

Do you actually need this path during the constructor? If you don't need it until the main page cycle begins, consider deferring it - just using a regular property; something like

在構造函數中你真的需要這個路徑嗎?如果您在主頁循環開始之前不需要它,請考慮推遲它 - 只需使用常規屬性;就像是

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

Then when this is used during the page cycle, it should be fine. You could cache it if you really want to, but I don't imagine this is going to be a bottleneck:

然后,當在頁面循環期間使用它時,它應該沒問題。如果你真的想要,你可以緩存它,但我不認為這將是一個瓶頸:

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

#3


0  

Try going through the ControllerContext. Forgive my syntax, but it should something like this:

嘗試瀏覽ControllerContext。請原諒我的語法,但它應該是這樣的:

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

If Server is still null in that situation, are you running outside of a web request (ie. in a test)?

如果在這種情況下服務器仍為空,您是否在Web請求之外運行(即在測試中)?


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2009/01/22/7250f5ad318aee2de468e8201b5cdf02.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com