IHostingEnvironment.WebRootPath is null when using EF7 commands

asp.net-core asp.net-core-mvc entity-framework-core



When I try to add a migration to my code, e.g: dnx ef migrations add initial,

the env.WebRootPath in Startup(IHostingEnvironment env) is null.

This will give me compilation errors when adding a new migration or updating the database.

The Code

In the Startup.cs class I have these lines in the constructor:

public Startup(IHostingEnvironment env)
    // ...
    // ...
    _hostingEnvironment = env;

Here env.WebRootPath is null and in the Initialize function this throws an exception.

In the ConfigureServices function of the Startup.cs I resolve my class dependencies:

public void ConfigureServices(IServiceCollection services)
    // ...
    services.AddInstance<IMyService>(new MyService(_hostingEnvironment.WebRootPath))
    // Note: _hostingEnvironment is set in the Startup constructor.
    // ...


  • I can build, run, and deploy the code fine. Everything works!

  • However I made a change in the model and want to add a migration with this command: dnx ef migrations add MyMigration then I see the compilation errors in the package manager console.

  • I am using ASP 5 web application, and Entity Framework 7

2/10/2016 7:31:37 PM

Accepted Answer

There is an issue reported on github regarding my problem:


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");
2/10/2016 7:34:41 PM

Popular Answer

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.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow