ASP.NET Core 3.1 WebRoot Path

Viewed 10664

I am pushing an external file into the wwwroot folder of my ASP.NET Core 3.1 application. I need to reference the path to provide a constructor variable during the services wire up.

In the Startup class I have added the IWebHostEnvironment to the constructor parameters:

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
  Configuration = configuration;
  _env = env;
}

When debugging, it seems that _env.WebRootPath returns the path as it is in my source folder, rather than the path being executed, i.e.

It returns: <path to my source code>/wwwroot

Instead of the execution relative path: <path to my source code>/bin/Debug/netcoreapp3.0/wwwroot

How do i get it to return the correct, execution relative path?

4 Answers

It's because by default the content-root path is the directory where the project is located rather than its output.

If you want to change that behavior, you have to call this line when building the web-host.

.UseContentRoot(AppContext.BaseDirectory);

Then the path will change to <ProjectPath>\Debug\netcoreapp3.1 or whatever you are compiling to.

private readonly IWebHostEnvironment _env;

public HomeController(IWebHostEnvironment env)
{
   _env = env;
}

public ActionResult Index()
{
   string contentRootPath = _env.ContentRootPath;
   string webRootPath = _env.WebRootPath;
   return Content(contentRootPath + "\n" + webRootPath);
}

It worked for me

string applicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Related