如果要得到传统的ASP.Net应用程序中的相对路径或虚拟路径对应的服务器物理路径,只需要使用使用Server.MapPath()方法来取得Asp.Net根目录的物理路径,如下所示:
//Classic ASP.NET
public classHomeController : Controller
{publicActionResult Index()
{string physicalWebRootPath = Server.MapPath("~/");returnContent(physicalWebRootPath);
}
}
但是在ASPNET Core中不存在Server.MapPath()方法,Controller基类也没有Server属性。
在Asp.Net Core中取得物理路径:
从ASP.NET Core RC2开始,可以通过注入 IHostingEnvironment 服务对象来取得Web根目录和内容根目录的物理路径,如下所示:
usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Mvc;namespaceAspNetCorePathMapping
{public classHomeController : Controller
{private readonlyIHostingEnvironment _hostingEnvironment;publicHomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment=hostingEnvironment;
}publicActionResult Index()
{string webRootPath =_hostingEnvironment.WebRootPath; //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Web\wwwrootstring contentRootPath =_hostingEnvironment.ContentRootPath; //F:\数据字典\Centa.Data.Dictionary\Centa.Data.Webreturn Content(webRootPath + "\n" +contentRootPath);
}
}
}
ASP.NET Core RC1
在ASP.NET Core RC2之前 (就是ASP.NET Core RC1或更低版本),通过 IApplicationEnvironment.ApplicationBasePath 来获取 Asp.Net Core应用程序的根目录(物理路径) :
usingMicrosoft.AspNet.Mvc;usingMicrosoft.Extensions.PlatformAbstractions;namespaceAspNetCorePathMapping
{public classHomeController : Controller
{private readonlyIApplicationEnvironment _appEnvironment;publicHomeController(IApplicationEnvironment appEnvironment)
{
_appEnvironment=appEnvironment;
}publicActionResult Index()
{returnContent(_appEnvironment.ApplicationBasePath);
}
}
}