![](/img/trans.png)
[英]ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller
[英]How Can I Find The Path To A Folder from a Controller Constructor in ASP.NET MVC?
我試圖在我的網站根目錄中獲取到文件夾的路徑,並將其保存到類屬性,當調用我的控制器構造函數時:
public TestController:Controller{
string temp;
public TestController(){
temp = "";
}
}
我嘗試了以下方法:
temp = Server.MapPath("~/TheFolder/"); // Server is null - error.
temp = Request.PhysicalApplicationPath + @"TheFolder\"; // Request is null - error.
有任何想法嗎?
AppDomain.CurrentDomain.BaseDirectory將為您提供站點的根目錄。 所以:
temp = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TheFolder");
(感謝Marc Gravell的評論進行更新)
在構造函數期間,您實際上是否需要此路徑? 如果在主頁周期開始之前不需要它,請考慮將其推遲-只需使用常規屬性即可; 就像是
public string BasePath {
get { return Server.MapPath("~/TheFolder/"); }
}
然后,在頁面周期中使用它時,應該沒問題。 如果確實願意,可以緩存它,但我不認為這會成為瓶頸:
private string basePath;
public string BasePath {
get {
if(basePath == null) basePath = Server.MapPath("~/TheFolder/");
return basePath;
}
}
嘗試遍歷ControllerContext。 原諒我的語法,但是應該是這樣的:
base.[Controller?]Context.HttpContext.Server.MapPath();
如果在這種情況下Server 仍然為 null,那么您是否正在Web請求之外運行(即在測試中)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.