In this article we will discuss IWebHostEnvironment in ASP.Net Core.
Here we discuss why Server.MapPath not working in ASP.Net Core and what is the alternative solution for using the functionality in ASP.Net Core.
Before start this article, please visit our previous article How to use ViewBag in ASP.Net Core MVC
Microsoft has permanently removed Server.MapPath function from .Net Core and introduced a new interfaces IHostingEnvironment for .Net Core 2.0 and IWebHostEnvironment for .Net Core 3.0 onwards.
What is IWebHostEnvironment
IWebHostEnvironment has replaced IHostingEnvironment in .Net Core 3.0 onwards.
Both these interfaces need to be injected as dependency in the Controller and then later used throughout the Controller.
Both these interfaces have two properties.
1. WebRootPath – Path of the www folder.
2. ContentRootPath – Path of the root folder which contains all the Application files.
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Hosting;
Using IWebHostEnvironment
In the below example, the IHostingEnvironment is injected in the Controller and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.
Output
When we run the application you can see like below screenshot we get the result of content root path and web root path.
You can see now WebRootPath fetch the path of wwwroot folder whereas ContentRootPath fetch path of content of our application.
Summary
Post a Comment