A-S*_*ani 9 entity-framework-core asp.net-core-mvc asp.net-core
问题
当我尝试迁移添加到我的代码,例如:dnx ef migrations add initial,
在env.WebRootPath中Startup(IHostingEnvironment env)为空.
这将在添加新迁移或更新数据库时给出编译错误.
代码
在Startup.cs类中,我在构造函数中有以下行:
public Startup(IHostingEnvironment env)
{
// ...
MyStaticClass.Initialize(env.WebRootPath);
// ...
_hostingEnvironment = env;
}
Run Code Online (Sandbox Code Playgroud)
这env.WebRootPath是null,在Initialize函数中抛出异常.
在Startup.cs的ConfigureServices函数中,我解决了我的类依赖关系:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddInstance<IMyService>(new MyService(_hostingEnvironment.WebRootPath))
// Note: _hostingEnvironment is set in the Startup constructor.
// ...
}
Run Code Online (Sandbox Code Playgroud)
笔记
我可以构建,运行和部署代码.一切正常!
但是我在模型中进行了更改,并希望使用此命令添加迁移:dnx ef migrations add MyMigration然后我在包管理器控制台中看到编译错误.
我正在使用ASP 5 Web应用程序和Entity Framework 7
Ric*_*ane 30
如果从项目的根目录中无意中删除了wwwroot文件夹,则env.WebRootPath也可以为null.将wwwroot文件夹添加到项目的根目录也可以解决此问题.
A-S*_*ani 11
关于我的问题,github上报告了一个问题:
https://github.com/aspnet/EntityFramework/issues/4494
我现在在评论中使用了解决方法似乎工作正常:
if (string.IsNullOrWhiteSpace(_env.WebRootPath))
{
env.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot");
}
Run Code Online (Sandbox Code Playgroud)
我相信这个线程是找出这个问题答案的最佳线程。
方法一:
我花了一些时间寻找答案,我发现解决这个问题而不是检查路径是否存在(在控制器或方法中)的方法是更新您的 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>();
Run Code Online (Sandbox Code Playgroud)
这样,您将确保将有 webroot 文件夹准备好在其中放置文件,并且 _environment.webRootPath 不会为空,您甚至可以自定义文件夹的名称。
方法二
执行此操作的第二个选项是从 Visual Studio 级别在项目中手动添加“wwwroot”文件夹。程序应该选择它并分配为 wwwroot 文件夹:
| 归档时间: |
|
| 查看次数: |
12700 次 |
| 最近记录: |