【问题标题】:Why IConfigurationRoot GetConnectionString is returning null?为什么 IConfigurationRoot GetConnectionString 返回 null?
【发布时间】:2018-08-29 15:35:38
【问题描述】:

我正在尝试在我的 Asp.net Core 项目中读取 .json 文件。

打印

dbConfig.json

{
  "AzureCosmosDb": {
    "EndpointUrl": "https://localhost:8081",
    "PrimaryKey": "C2y6yDjf5/R++4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
    "DatabaseId": "Cosmoso"
  },
  "Oracle12c": {

  }
}

dbConfig.Json中搜索文件中的值的代码:

public static string GetConnectionString(string fileJson, string conexao)
{
  var builder = new ConfigurationBuilder().AddJsonFile(fileJson);

  Configuration = builder.Build();

   string connection = Configuration.GetConnectionString("AzureCosmosDb:DatabaseId");
   return connection;
}

方法返回null,怎么回事?

【问题讨论】:

    标签: c# asp.net-core


    【解决方案1】:

    Configuration.GetConnectionString 查找名称为 "ConnectionStrings" 的配置部分,因此您必须像这样调整配置才能使该方法起作用:

    {
      "ConnectionStrings": {
        "AzureCosmosDb": {
          "DatabaseId": "Cosmoso"
        }
      }
    }
    

    但由于您还有其他不是连接字符串的配置,我建议您根本不要使用GetConnectionString,而直接检索该值:

    string connection = Configuration["AzureCosmosDb:DatabaseId"];
    

    【讨论】:

      猜你喜欢
      • 2022-12-26
      • 2016-12-28
      • 1970-01-01
      • 2015-11-25
      • 2015-07-04
      • 2019-09-29
      • 2015-02-25
      • 2015-10-21
      • 2021-08-12
      相关资源
      最近更新 更多