Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get access to the IWebHostEnvironment from within an ASP.NET Core 3 controller?

I would like to be able to browse a directory in the web root (such as my \img directory or \pdf directory) from code within a controller.

I would like to use something like the following where env is an instance of IWebHostEnvironment:

var provider = env.WebRootFileProvider;
var path = env.WebRootPath;

I'm not sure how to get an instance of IWebHostEnvironment from within a controller. How can this be done?

like image 372
Intensivist Avatar asked Dec 12 '19 12:12

Intensivist


People also ask

What is IWebHostEnvironment in .NET Core?

IWebHostEnvironment Provides information about the web hosting environment an application is running in. belongs to namespace Microsoft.AspNetCore.Hosting. The IWebHostEnvironment interface need to be injected as dependency in the Controller and then later used throughout the Controller.

How do I get WebRootPath in .NET Core?

The WebRootPath and ContentRootPath are accessed using the interfaces IHostingEnvironment (. Net Core 2.0) and IWebHostEnvironment (. Net Core 3.0) in ASP.Net Core. The IHostingEnvironment is an interface for .

What is IWebHostBuilder in ASP.NET Core?

UseIIS(IWebHostBuilder) Configures the port and base path the server should listen on when running behind AspNetCoreModule. The app will also be configured to capture startup errors. UseIISIntegration(IWebHostBuilder) Configures the port and base path the server should listen on when running behind AspNetCoreModule.


1 Answers

You can use dependency injection to inject an IWebHostEnvironment instance into your controller. Either in the constructor:

public class MyController : Controller
{
    private readonly IWebHostEnvironment _env;
    public MyController(IWebHostEnvironment env)
    {
        _env = env;
    }
}

or in any or the controller's method:

public class MyController : Controller
{
    [HttpGet]
    public IActionResult Me([FromServices] IWebHostEnvironment env)
    {
        return View();
    }
}

Note that the default WebRootFileProvider points to the wwwroot folder, so you need to ensure it exists, otherwise you'll get a NullFileProvider.

like image 114
Métoule Avatar answered Sep 20 '22 08:09

Métoule