神刀安全网

Getting the Web Root Path and the Content Root Path in ASP.NET Core

If you wanted to map relative or virtual paths to physical directories on the server in classic ASP.NET applications, you were always able to use the Server.MapPath() method to find the physical path of the web root directory like this:

// Classic ASP.NET  public class HomeController : Controller {     public ActionResult Index()     {         string physicalWebRootPath = Server.MapPath("~/");                  return Content(physicalWebRootPath);     } } 

In ASP.NET Core, however, the Server.MapPath() method doesn’t exist anymore. In fact, the Controller base class doesn’t even have a Server property.

Starting with ASP.NET Core RC2, the physical paths to both the web root and the content root directories can be retrieved by injecting and querying the IHostingEnvironment service:

using Microsoft.AspNet.Hosting; using Microsoft.AspNet.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;              return Content(webRootPath + "/n" + contentRootPath);         }     } } 

I have created a demo .NET Core application on my machine in the ~/Code/AspNetCorePathMapping directory. If I run it, the above controller action returns the following two paths:

Getting the Web Root Path and the Content Root Path in ASP.NET Core

Notice the distinction between web root and content root : The web root is the root directory from which static content is served, while the content root is the application base path.

Before ASP.NET Core RC2 — that is, up until ASP.NET Core RC1 — the application base path was available via IApplicationEnvironment.ApplicationBasePath instead of IHostingEnvironment.ContentRootPath :

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);         }     } } 

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Getting the Web Root Path and the Content Root Path in ASP.NET Core

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址