Accessing Web Root and Content Root Path's in ASP.NET Core

Web root is the root directory from which static content is served, while the content root is the application base path. In this article, we will see how to access them in Controller's.

In ASP.NET Core, 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.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace SampleDemo
{
    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);
        }
    }
}

The web root is the root directory from which static content is served, while the content root is the application base path.