Getting ConnectionStrings config settings from appsettings.json

2.3k Views Asked by At

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.

enter image description here

2

There are 2 best solutions below

3
On BEST ANSWER

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.

0
On

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];