What is the equivalent of Server.MapPath in ASP.NET Core?

ProfK picture ProfK · Mar 21, 2018 · Viewed 38.1k times · Source

I have this line in some code I want to copy into my controller, but the compiler complains that

The name 'Server' does not exist in the current context

var UploadPath = Server.MapPath("~/App_Data/uploads")

How can I achieve the equivalent in ASP.NET Core?

Answer

ashin picture ashin · Mar 21, 2018

UPDATE: IHostingEnvironment is deprecated. See update below.

In Asp.NET Core 2.2 and below, the hosting environment has been abstracted using the interface, IHostingEnvironment

The ContentRootPath property will give you access to the absolute path to the application content files.

You may also use the property, WebRootPath if you would like to access the web-servable root path (www folder by default)

You may inject this dependency into your controller and access it as follows:

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

UPDATE

IHostingEnvironment has been marked obsolete with .NET Core 3.0 as pointed out by @amir133. You should be using IWebHostEnvironment instead of IHostingEnvironment. Please refer to that answer below.

Microsoft has neatly segregated the host environment properties among these interfaces. Please refer to the interface definition below:

namespace Microsoft.Extensions.Hosting
{
  public interface IHostEnvironment
  {
    string EnvironmentName { get; set; }
    string ApplicationName { get; set; }
    string ContentRootPath { get; set; }
    IFileProvider ContentRootFileProvider { get; set; }
  }
}

namespace Microsoft.AspNetCore.Hosting
{
  public interface IWebHostEnvironment : IHostEnvironment
  {
    string WebRootPath { get; set; }
    IFileProvider WebRootFileProvider { get; set; }
  }
}