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?
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.
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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With