在以前asp.net MVC项目中的时候,获取当前项目的根目录非常容易,我们使用
Server.MapPath("~/");
WebAPI的控制器中应该是因
1. string basePath1 = AppContext.BaseDirectory;
2.string basePath2 =Path.GetDirectoryName(typeof(Program).Assembly.Location);
3.从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; string contentRootPath = _hostingEnvironment.ContentRootPath; //webRootPath: D:\后端项目\testCore\test.WebApi\wwwroot // contentRootPath: D:\后端项目\testCore\test.WebApi return Content(webRootPath + "\n" + contentRootPath); } } }