所以我试图让 .NET Core API 应用程序在不同的环境设置下运行。我一直在阅读文档,据我所知,我已按照说明进行操作。然而,当我在 VS 之外运行该服务时,由于无法找到连接字符串,它会崩溃。我显然错过了一些基本的东西。
我已经设置了两个配置文件launchSettings.json
“发展”与“阶段”
"profiles": {
"IIS Express": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Development": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Staging": {
"commandName": "Project",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
}
}
我有以下配置文件。
appsettings.json
appsettings.Development.json
appsettings.Staging.json
我的中也有以下代码Startup.cs
:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
当我调试这个时我可以看到.AddJsonFile($"appsettings.{env.EnvironmentName}.json"
正在加载预期的文件。但是,当我将其发布到目录并尝试运行它时connectionString
重视我们null
.
appsettings.json 不包含连接字符串的值。它位于两个环境相关文件中,定义如下:
"DefaultConnection": {
"ConnectionString":
"Server=name;Port=3307;Database=name;User Id=name;Password=name;"
},
因为这一切都在 VS 内工作,所以我确信这都是正确的。然而,当我尝试运行它时,BOOM!
dotnet MyDll.dll --launch-profile Staging
我刚刚注意到--launch-profile
仅适用于dotnet run
当我尝试运行该应用程序时,它正在寻找Production.json
文件。如何仅使用各种配置文件dotnet
命令,而不是dotnet run
命令?