从appsettings.json获取ConnectionStrings配置设置 [英] Getting ConnectionStrings config settings from appsettings.json
问题描述
在我的存储库类中,我有我的Config对象,看起来我的连接字符串在以下位置:
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
这是我的appsettings.json
的样子:
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
},
"ConnectionStrings": {
"myConnectionString": details..."
}
}
我正在尝试按以下方式阅读myConnectionString
:
I'm trying to read myConnectionString
as follows which is not working:
var cs = _config.GetSection("ConnectionStrings.myConnectionString").value;
我在做什么错了?
更新:
由于某种原因,我没有看到GetValue()
方法.我正在使用ASP.NET Core 2.0
.
UPDATE:
For some reason, I'm not seeing GetValue()
method. I'm using ASP.NET Core 2.0
.
推荐答案
问题似乎出在传递给GetSection()方法的字符串路径上.根据 ASP .NET Core配置文档,您应该使用"ConnectionStrings:myConnectionString"而不是"ConnectionStrings.myConnectionString".
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".
此外,如果您希望直接检索该值,则可能更喜欢使用GetValue()方法:
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"];
但是,老实说,我发现第一种方法更加简洁明了,因为GetValue()方法允许您指定默认值,以防在配置中找不到该属性.
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.
这篇关于从appsettings.json获取ConnectionStrings配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!