【问题标题】:.Net-Core configuration pull connection string wrong provider.Net-Core 配置拉取连接字符串错误的提供者
【发布时间】:2018-06-10 05:02:19
【问题描述】:

我正在尝试为我的 .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() 它返回 @ 987654327@.

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

【问题讨论】:

  • 您在哪里存储暂存配置?进入 appstettings.staging.json 或 appsettings.json ?
  • Staging 在应用程序设置中,localhost 正在开发中,我期待 localhost 但我正在登台

标签: c# configuration .net-core


【解决方案1】:

这是返回暂存版本而不是开发版本。然而,当我检查这是否是开发环境env.IsDevelopment() 它返回true。

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

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

转到 Debug 选项卡,然后确保 环境变量 部分的 ASPNETCORE_ENVIRONMENT 设置为 Staging,如下所示:

这样做env.IsDevelopment() 将返回false 和env.IsStaging() 将返回true。所以 appsettings.development.json 不会包含在您的配置中。

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

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

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

【讨论】:

  • 我很确定这会解决它,我会在早上确认。我想我需要分离出我的配置
  • 是的,最好的做法是按环境分开。
  • 谢谢,事实证明,这是连接字符串的嵌套深度超出了应有的程度,因此找不到。
  • 嗯...您在问题中的配置是正确的,所以我们没有看到这个问题:)
  • 是的,这解决了问题,因为我在将所有内容移至 appsettings.staging.json 时发现了它,但我想我也会记录我的错误,以防其他人来到这里仍然无法弄清楚为什么
猜你喜欢
  • 2021-10-29
  • 2019-05-08
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 2016-10-02
  • 1970-01-01
相关资源
最近更新 更多