Home  >  Article  >  Backend Development  >  What is the role of the IWebHostEnvironment interface in C# ASP.NET Core?

What is the role of the IWebHostEnvironment interface in C# ASP.NET Core?

PHPz
PHPzforward
2023-09-07 20:33:141229browse

C# ASP.NET Core 中 IWebHostEnvironment 接口的作用是什么?

IWebHostEnvironment provides information about web hosting environments and The application is running.

Belongs to the namespace Microsoft.AspNetCore.Hosting

The IWebHostEnvironment interface needs to be injected as a dependency into controller and then used throughout the controller.

The IWebHostEnvironment interface has two properties.

  • WebRootPath - The path to the www folder (gets or sets the absolute path to the directory containing the application content files for the web service)
  • ContentRootPath - Path to the root folder containing all application files (Gets or sets the IFileProvider pointing to the WebRootPath.)

Usage

We need to import the namespace

using Microsoft.AspNetCore.Hosting;

In the example below, IWebHostEnvironment is injected into the controller, and Assigned to the private property Environment, later used to get the WebRootPath and ContentRootPath.

Example

public class HomeController : Controller{
   private IWebHostEnvironment Environment;
   public HomeController(IWebHostEnvironment _environment){
      Environment = _environment;
   }
   public IActionResult Index(){
      string wwwPath = this.Environment.WebRootPath;
      string contentPath = this.Environment.ContentRootPath;
      return View();
   }
}

The above is the detailed content of What is the role of the IWebHostEnvironment interface in C# ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete