IHostingEnvironment.WebRootPath is null when using EF7 commands
There is an issue reported on github regarding my problem:
https://github.com/aspnet/EntityFramework/issues/4494
I used the workaround in the comments now it seems to be working fine:
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
The env.WebRootPath can also be null if the wwwroot folder has been inadvertantly removed from the root of your project. Adding a wwwroot folder to the root of your project will also fix this issue.
In my case, the problem was that the wwwroot folder was empty and VS didn't recognized it.
The solution: create a placeholder.txt in wwwroot.
Hope it helps.
This thread is I believe best one to find out the answer for this problem.
Method 1:
I spent a bit of time looking for answer and I figured out that the way to sort this out rather than check if path exists(in controller or methods) is to update your Program.cs:
public static async Task Main(string[] args)
{
IWebHost webHost = CreateWebHostBuilder(args).Build();
await webHost.RunAsync();
}
private static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(Directory.GetCurrentDirectory())
.UseWebRoot("wwwroot")
.UseStartup<Startup>();
This way you will ensure that there will be webroot folder ready for placing files inside it and _environment.webRootPath will not be null and also you can even customize the name of the folder.
Method 2
The second option to do this is to manually add "wwwroot" folder in the project from Visual Studio level. The program should pick this up and allocate as wwwroot folder: