配置GetSection返回对象部分的空值 [英] Configuration GetSection returns null value for object sections
问题描述
您好,我在 .NET Core应用
中使用了 json
配置文件,但我不明白为什么我要为对象的子节得到null值:>
Hello i am using a a json
configuration file within a .NET Core App
and i do not understand why i get the value null for subsections that are objects:
{
"tt": {
"aa":3,
"x":4
},
"Url":333,
"Config": {
"Production": {
"RedisAddress": {
"Hostname": "redis0",
"Port": 6379
},
"OwnAddress": {
"Hostname": "0.0.0.0",
"Port": 9300
}
},
"Dev": {
"RedisAddress": {
"Hostname": "redis0",
"Port": 6379
},
"OwnAddress": {
"Hostname": "0.0.0.0",
"Port": 9300
},
"Logger": "logger.txt"
}
}
}
当我尝试 GetSection("Config")
或 GetSection("tt")
时,我得到的值是 null
.但是它会返回原始类型的值,例如我的 Url
.
When i try GetSection("Config")
or GetSection("tt")
i get the value null
.It however returns the value for primitive types like in my case Url
.
有趣的是,如果我在 configuration.Providers [0] .Data
中查看,我会像图片中一样呈现所有内容:
What is funny is that if i peek inside the configuration.Providers[0].Data
i have all the content present like in the picture:
为什么它为 object
类型返回null?
Why does it return null for object
types?
代码
WebHostBuilder builder = new WebHostBuilder();
builder.UseStartup<Startup>();
string appPath = AppDomain.CurrentDomain.BaseDirectory;
string jsonPath = Path.Combine(Directory.GetParent(Directory.GetParent(appPath).FullName).FullName, "appsettings.json");
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(appPath)
.AddJsonFile(jsonPath, optional: true, reloadOnChange: true)
.Build();
var sect = configuration.GetSection("Config");//has value null
var sect2 = configuration.GetSection("tt");//has value null
var sect3 = configuration.GetSection("Url"); has value 333
推荐答案
两个答案( TanvirArjel 和
Both answers (TanvirArjel and Kirk Larkin) are correct. I am just going to clarify things for you and provide another way of getting the value form the configuration file.
要从 appsettings.json
中获取一个值,您需要将该值的路径(以冒号分隔的)传递给 configuration
.
To get a value from appsettings.json
you need to pass the path of the value (colon-separated
) to the configuration
.
有多种方法可以在不将节绑定到类的情况下获取值.例如:
There are different ways to get the value without binding the section to a class. E.g.:
var aaAsString = configuration["tt:aa"]; //will return the value as a string "3".
//To get the actual value type you need to cast them
var aa1 = configuration.GetValue<int>("tt:aa"); //returns 3.
var aa2 = configuration.GetSection("tt").GetValue<int>("aa");
var aa3 = configuration.GetSection("tt").GetValue(typeof(int), "aa");
这篇关于配置GetSection返回对象部分的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!