【发布时间】:2017-05-13 04:56:27
【问题描述】:
我正在尝试绑定到应由 appsettings.json 文件填充的自定义配置对象。
我的 appsettings 看起来有点像:
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Settings": {
"Foo": {
"Interval": 30,
"Count": 10
}
}
}
设置类如下所示:
public class Settings
{
public Foo myFoo {get;set;}
}
public class Foo
{
public int Interval {get;set;}
public int Count {get;set;}
public Foo()
{}
// This is used for unit testing. Should be irrelevant to this question, but included here for completeness' sake.
public Foo(int interval, int count)
{
this.Interval = interval;
this.Count = count;
}
}
当我尝试将配置绑定到它工作的最低级别的对象时:
Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();
myFoo 正确地具有 Interval 和 Count,其值分别设置为 30 和 10。
但这不是:
Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();
mySettings 有一个空的foo。
令人沮丧的是,如果我使用调试器,我可以看到从 appsettings.json 文件中读取了必要的数据 。我可以进入Configuration => Non-Public Members => _providers => [0] => Data 并查看我需要的所有信息。它只是不会绑定复杂的对象。
【问题讨论】:
-
你的设置类是什么样子的?
-
Foo和Settings是如何定义的? -
@haim770 我已经添加了类定义。
-
您的设置属性是
myFoo,但您的设置是“Foo”...
标签: c# json asp.net-core .net-core