Getting ConnectionStrings config settings from appsettings.json

家住魔仙堡 提交于 2019-12-11 15:49:42

问题


In my repository class, I have my Config object and looks like my connection string is under:

Config > Providers > Microsoft.Configuration.Json.JsonConfigurationProvider > Data > ConnectionStrings.myConnectionString

This is what my appsettings.json looks like:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "myConnectionString": details..."
  }
}

I'm trying to read myConnectionString as follows which is not working:

var cs = _config.GetSection("ConnectionStrings.myConnectionString").value;

What am I doing wrong?

UPDATE: For some reason, I'm not seeing GetValue() method. I'm using ASP.NET Core 2.0.


回答1:


The issue seems to lie in the string path you are passing to the GetSection() method. According to the ASP.NET Core Configuration documentation you should use "ConnectionStrings:myConnectionString" instead of "ConnectionStrings.myConnectionString".

Plus, if you wish to retrieve the value directly you may prefer to use the GetValue() method instead:

var cs = _config.GetValue("ConnectionStrings:myConnectionString", "");

If you prefer, you can also use the index notation as:

var cs = _config["ConnectionStrings:myConnectionString"];

But I honestly find the first approach more clean and elegant as the GetValue() method allows you to specify a default value in case the property is not found in the configuration.




回答2:


Configuration API provides extension method for IConfiguration to simplify reading ConnectionStrings section:

// using Microsoft.Extensions.Configuration;

string connectionString = _config.GetConnectionString("myConnectionString");

what it does is return configuration?.GetSection("ConnectionStrings")?[name];



来源:https://stackoverflow.com/questions/50010942/getting-connectionstrings-config-settings-from-appsettings-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!