Header add


In this article we discuss about what is the difference between IHostingEnvironment and IWebHostEnvironment in ASP.Net Core. If you are new to .NET Core MVC please follow the previous article playlist .NET Core MVC Series.

As you know in ASP .NET & ASP .NET MVC application Server.MapPath is used, but in .NET Core application Microsoft has permanently removed Server.MapPath function and introduced a new interfaces IHostingEnvironment for .Net Core 2.0 and IWebHostEnvironment for .Net Core 3.0 and onwards.

Difference of  IHostingEnvironment and IWebHostEnvironment

The IHostingEnvironment is an interface for .Net Core 2.0 and IWebHostEnvironment has replaced IHostingEnvironment in .Net Core 3.0.

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.
  • WebRootPath – Path of the www folder ( using this path you can access all static files)
  • ContentRootPath – Path of the root folder which contains all the Application files. ( using this you can get all the application file in root folder)
Before using IHostingEnvironment and IWebHostEnvironment you need to import the below namespace.

IHostingEnvironment

The IHostingEnvironment is injected in the Controller and assigned to the private property Environment and then used to get the WebRootPath and ContentRootPath as on below;


When you run the application you can see the result as below;

A warning was showing to use IWebHostEnvironment as we create application in target framework 3.1
IWebHostEnvironment

The IWebHostEnvironment is injected in the Controller and assigned to the private property Environment and then used to get the WebRootPath and ContentRootPath as on below;
When we run the application you can see the same output as like in IHostingEnvironment.


  Summary
     In this tutorial we discussed IHostingEnvironment vs IWebHostEnvironment in ASP.Net Core. If have any question related to this topic then give your feedback.





You May Also Like...

Post a Comment

Previous Post Next Post