Server.MapPath Equivalent in ASP.NET Core

Web Developers who use Microsoft technologies have always relied on the Server.MapPath method to resolve file paths in classic ASP and ASP.NET Web Forms and MVC versions up to and including 5. This method has not been included in ASP.NET Core, so what do you use instead?

One of the services that's included by default when you create an ASP.NET Core application is IHostingEnvironment. The service has two properties of particular interest: ContentRootPath and WebRootPath.

ContentRootPath resolves to the application's base path. This is the location of the web.config, project.json, source code and other files not intended to be served to browsers. The WebRootPath property gets the physical file path to the directory that houses files intended to be browsable. By default, this is the wwwroot folder in the application.

Great! So how do you access the IHostingEnvironment properties? It's easy, really. Since IHostingEnvironment is added to the application's services by the framework, you can simply inject the service into the constructor of your controller and the built-in dependency injection system will resolve it for you:

You will need to add a using directive for Microsoft.AspNetCore.Hosting to make IHostingEnvironment available to your controller class, and you will have to create a constructor for the controller.

Changing WebRootPath

As I mentioned, the default location of WebRootPath is the wwwroot folder, but what if for some reason you wanted to change that? You can use the UseWebRoot extension method on the WebHostBuilder class to set your preferred location. You can do this in the Main method of the Program class:

You might also like...