我无法让我发布的ASP.net核心应用程序切换到我的appsettings.production.json文件中使用连接字符串.
我已经设置了launchSettings来为我的开发和生产配置文件使用ASPNETCORE_ENVIRONMENT环境变量.当我切换配置文件并在visual studio中运行它时,我的连接字符串会正确更改.
当我在我的Ubuntu服务器上运行已发布的应用程序时,它不会切换.我在我的服务器上将ASPNETCORE_ENVIRONMENT变量设置为"Production".我还验证了appSettings.json和appSettings.production.json都存在于应用程序的根目录中.
我的appsettings.json文件:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;password=dev;database=testdb;sslmode=none",
}
}
Run Code Online (Sandbox Code Playgroud)
我的appsettings.production.json文件:
{
"ConnectionStrings": {
"DefaultConnection": "server=localhost;user id=root;password=prod;database=testdb;sslmode=none"
}
}
Run Code Online (Sandbox Code Playgroud)
我的launchSettings.json文件:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:50824/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "home/index",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express (Production)": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "home/index",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Production"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的Startup.cs:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
Console.WriteLine("Root Path: " + env.ContentRootPath);
Console.WriteLine("Connection String: " + Configuration.GetConnectionString("DefaultConnection"));
}
Run Code Online (Sandbox Code Playgroud)
我已经引用了这些问题,但没有运气:
事实证明,官方文档中的这个“注释”非常重要:
在 Windows 和 macOS 上,指定的环境名称不区分大小写。无论您将变量设置为 Development 还是 development 或 DEVELOPMENT,结果都是一样的。但是,Linux 默认是区分大小写的操作系统。环境变量、文件名和设置应假设区分大小写以获得最佳实践。
主要是“默认情况下 Linux 是区分大小写的操作系统”这一行!!!!!!!哎呀:)
一旦我将环境变量更改为“生产”而不是“生产”,它就起作用了。
进一步说明:
关键是理解Startup.cs启动方法中的这行代码:
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
Run Code Online (Sandbox Code Playgroud)
它将 {env.EnvironmentName} 替换为您的环境变量,因此如果您在 linux 中操作,它需要与您的文件名完全匹配。在我的例子中是“appSettings.production.json”,所以 ASPNETCORE_ENVIRONMENT 必须是“production”。
| 归档时间: |
|
| 查看次数: |
3487 次 |
| 最近记录: |