c# - ASPNET 核心 : Wrong Value for ContentRootPath

标签 c# asp.net .net .net-core

我有一个具有以下配置的 ASP.NET 核心应用程序:

public Startup(IHostingEnvironment hostingEnvironment)
{
    _configuration = new ConfigurationBuilder()
        .SetBasePath(hostingEnvironment.ContentRootPath)
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", true)
        .AddEnvironmentVariables()
        .Build();
}

当我发布应用程序并使用应用程序目录中的 dotnet MyApp.dll 运行它时,它运行没有任何问题。当我执行命令 dotnet/dir1/dir2/MyApp.dll 时,它无法加载 appsettings.json 文件。我做了一些挖掘,发现 ContentRootPath 设置为我运行 dotnet 命令的目录,而不是应用程序的实际目录。谁能告诉我如何解决这个问题?

最佳答案

我也遇到了同样的问题。我经常将我的代码存储在包含多个项目的/src 文件夹中。因此,我想从 CLI 执行以下操作:

cd /c/code/repo
dotnet restore /src/solution.sln
dotnet build /src/solution.sln
dotnet run /src/project/project.csproj

前 2 个没有问题,但 .NET Core 2.0 的 CLI 无法将 .SetBasePath(env.ContentRootPath) 识别为构建项目的路径。相反,它使用我在 CLI 上的当前路径。

这导致:

Unhandled Exception: System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional. The physical path is 'C:\code\repo\appsettings.json'.

我让它工作的唯一方法是进入那个目录:

cd /src/project
dotnet run project.csproj

这很好,但如果我想重建解决方案,那么我需要导航回我的 .sln 所在的/src,这非常烦人。

似乎是 CLI 中的错误。

关于c# - ASPNET 核心 : Wrong Value for ContentRootPath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41934783/

相关文章:

具有保留关键字的 C# 枚举

.net - 如何在 xaml 中绑定(bind)到动态 xpath?

c#初学者-如何使用if语句检查文本框是否为空?

c# - 如何使用 DocumentFormat.OpenXml 在 Word 模板中编辑书签并将其另存为新的 PDF 文件?

c# - 消息在进行事务处理时未到达 MSMQ

c# - 在 Word 2016 中从 Imanage 打开文档

c# - Ogre3D:相对于自定义中心点的旋转

c# - 无法使用 RESP 在 Redis 服务器上执行命令

jquery - 使用 jQuery 从 iFrame 中的元素获取值

c# - MVC6 自定义 IModelBinder,Beta8 变了?