In this article I will explain with an example, how to use IWebHostEnvironment interface in ASP.Net Core (.Net Core 8) Razor Pages.
Note: For beginners in ASP.Net Core (.Net Core 8) Razor Pages, please refer my article ASP.Net Core 8 Razor Pages: Hello World Tutorial with Sample Program example.
 
 

What is IWebHostEnvironment

The IWebHostEnvironment is an interface for .Net Core 3.0.
The IWebHostEnvironment interface need to be injected as dependency in the PageModel and then later used throughout the PageModel.
The IWebHostEnvironment interface 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 IWebHostEnvironment is injected in the PageModel and assigned to the private property Environment and later used to get the WebRootPath and ContentRootPath.
public class IndexModel : PageModel
{
    private IWebHostEnvironment Environment;
 
    public IndexModel(IWebHostEnvironment _environment)
    {
        this.Environment = _environment;
    }
 
    public void OnGet()
    {
        string wwwPath  =  this.Environment.WebRootPath;
        string contentPath  =  this.Environment.ContentRootPath;
    }
}
 
 

Screenshot

Using IWebHostEnvironment in ASP.Net Core Razor Pages