1

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

3 Comments

Thank you! Using a colon fixed the issue. I also wanted to use the GetValue() method but for some reason, it's not available to me. See update in original post. Thank you again for your help.
The method lies in the Microsoft.Extensions.Configuration namespace. Are you using it? If not, then try and you should then be able to access it.
It's in that namespace but it's actually an extension via Microsoft.Extensions.Configuration.Binder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.