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
.
Configuration API provides extension method for
IConfiguration
to simplify readingConnectionStrings
section:what it does is
return configuration?.GetSection("ConnectionStrings")?[name];
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:
If you prefer, you can also use the index notation as:
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.