gpt4 book ai didi

c# - .Net-Core 配置拉取连接字符串错误的提供者

转载 作者:行者123 更新时间:2023-11-30 12:20:38 24 4
gpt4 key购买 nike

我正在尝试为我的 .Net-core 2 应用程序设置环境配置。我有 2 个 appSettings 配置。

appSettings.json

"ConnectionStrings": {
"DefaultConnection": "Server=staging.com;Database=staging;User Id=staging;Password=pwd"
}

appsettings.development.json

"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=staging;User Id=local;Password=pwd"
}

在我的 Startup.cs 中,我的配置设置如下:

public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}

当我去抓取连接字符串时。

var connectionString = Configuration.GetConnectionString("DefaultConnection");

这将返回 appsettings.json 而不是 appsettings.development.json 但是当我检查这是否是开发环境时 env.IsDevelopment () 它返回 true

如何从我的配置中获取正确的连接字符串?

最佳答案

This is returning the staging one instead of the development. Yet when I check if this is the development environment env.IsDevelopment() it returns true.

您正在获取开发配置,因为您仍在开发环境中,这就是 env.IsDevelopment() 返回 true 的原因。

要告诉 ASP.Net Core 您正处于 Staging 环境中,您需要通过项目属性进行配置并设置环境属性。

转到 Debug 选项卡,然后确保 Environment variables 部分将 ASPNETCORE_ENVIRONMENT 设置为 Staging,如下所示:

enter image description here

这样做 env.IsDevelopment() 将返回 falseenv.IsStaging() 将返回 true。因此 appsettings.development.json 不会包含在您的配置中。

因为没有appsettings.staging.json,所以你会得到appseting.json设置然后是你要找的DefaultConnection .

旁注:您应该为暂存环境创建一个单独的文件appsettings.staging.json,因为appseting.json 应该只包含通用配置适用于所有环境。每个环境 appsettings.[environment].json 都应该添加新设置或覆盖通用设置。

旁注:确保 ConnectionStrings 部分的路径位于根级别

关于c# - .Net-Core 配置拉取连接字符串错误的提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50780705/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com