在传统的Asp.Net应用程序中,我们要获取相对路径或虚拟路径对应的服务器物理路径,我们只需要使用Server.MapPath()方法就可以来取得Asp.Net根目录的物理路径:
public class HomeController : Controller{
public ActionResult Index()
{
string path = Server.MapPath("~/");
return Content(path);
}
} 但在Asp.Net Core中不存在Server.MapPath()方法,Controller基类中没有Server属性。如果要在Asp.Net Core中取得物理路径,我们需要通过注入IHostingEnvironment服务对象来取得Web根目录和内容目录的物理路径:
public class HomeController : ExcelController
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
string webRootePath = _hostingEnvironment.WebRootPath;
string contentRootPath = _hostingEnvironment.ContentRootPath;
return Content(webRootePath + "\n" + contentRootPath);
}
}其中webRootPath:一般用于存放我们的静态资源文件,默认为wwwroot,当然我们可以对其进行修改,而contentRootPath则是我们的程序运行的根目录。

微信扫码查看本文
发表评论