如果要得到傳統的ASP.Net應用程序中的相對路徑或虛擬路徑對應的服務器物理路徑,只需要使用使用Server.MapPath()方法來取得Asp.Net根目錄的物理路徑,如下所示:
// Classic ASP.NET public class HomeController : Controller { public ActionResult Index() { string physicalWebRootPath = Server.MapPath("~/"); return Content(physicalWebRootPath); } }
但是在ASPNET Core中不存在Server.MapPath()方法,Controller基類也沒有Server屬性。
在Asp.Net Core中取得物理路徑:
從ASP.NET Core RC2開始,可以通過注入 IHostingEnvironment 服務對象來取得Web根目錄和內容根目錄的物理路徑,如下所示:
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; namespace AspNetCorePathMapping { public class HomeController : Controller { private readonly IHostingEnvironment _hostingEnvironment; public HomeController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public ActionResult Index() { string webRootPath = _hostingEnvironment.WebRootPath; //F:\數據字典\Centa.Data.Dictionary\Centa.Data.Web\wwwroot string contentRootPath = _hostingEnvironment.ContentRootPath; //F:\數據字典\Centa.Data.Dictionary\Centa.Data.Web return Content(webRootPath + "\n" + contentRootPath); } } }
ASP.NET Core RC1
在ASP.NET Core RC2之前 (就是ASP.NET Core RC1或更低版本),通過 IApplicationEnvironment.ApplicationBasePath 來獲取 Asp.Net Core應用程序的根目錄(物理路徑) :
using Microsoft.AspNet.Mvc; using Microsoft.Extensions.PlatformAbstractions; namespace AspNetCorePathMapping { public class HomeController : Controller { private readonly IApplicationEnvironment _appEnvironment; public HomeController(IApplicationEnvironment appEnvironment) { _appEnvironment = appEnvironment; } public ActionResult Index() { return Content(_appEnvironment.ApplicationBasePath); } } }