Server.MapPath in ASP.NET Core

25 January 2023

Long time ago we used Server.MapPath to get physical directory of provided relative or virtual path. In Core 3 and above we use IWebHostEnvironment

public class HomeController : Controller
{
    private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController (IWebHostEnvironment webHostEnvironment)
    {
        _webHostEnvironment= webHostEnvironment;
    }

    public IActionResult Index()
    {
        string webRootPath = _webHostEnvironment.WebRootPath;
        string contentRootPath = _webHostEnvironment.ContentRootPath;

        return Content("webRootPath: " + webRootPath + ", contentRootPath: " + contentRootPath);
    }
}