我有一个具有以下配置的 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/