Search code examples
c#.netasp.net-core.net-7.0

WebRootPath is null in ASP.NET Core MVC application


Having no prior experience with .NET (7.0) i have created a clean ASP.NET MVC application using

dotnet new mvc -n MyApp

Now i need the application to read and write some PDF-files inside wwwroot (user uploads PDF and gets a modifed PDF in return).

I have injected it in the default HomeController like

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

I have also included Microsoft.AspNetCore.Hosting.

When trying to use the WebRootPath like

var outputPath = Path.Combine(_env.WebRootPath, "output.pdf");

the _env.WebRootPath is null and the _env.ContentRootPath is C:/.../MyApp/bin/Debug/net7.0 and not C:/.../MyApp like i would expect.

What am i missing? Shouldn't this work out of the box?


Solution

  • I have managed to solve it by using the template ASP.NET Core Web App (Model-View-Controller) in the Visual Studio "Create a new project"-wizard instead of using dotnet new mvc.

    Not sure what caused the original issue though, but i suspect it lies somewhere in the differences between the default configurations created by the wizard's template and dotnet new mvc.