Nec*_*ras 5 c# json .net-core asp.net-core
我正在尝试绑定到应该由 appsettings.json 文件填充的自定义配置对象。
我的 appsettings 看起来有点像:
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Settings": {
"Foo": {
"Interval": 30,
"Count": 10
}
}
}
Run Code Online (Sandbox Code Playgroud)
设置类如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将 Configuration 绑定到最低级别的对象时,它可以工作:
Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();
Run Code Online (Sandbox Code Playgroud)
myFoo正确地将 anInterval和 aCount的值分别设置为 30 和 10。
但这不会:
Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();
Run Code Online (Sandbox Code Playgroud)
mySettings有一个 null foo。
无奈的是,如果我使用调试器,我可以看到必要的数据是从appsettings.json文件中读取。我可以进入Configuration => Non-Public Members => _providers => [0] => Data并查看我需要的所有信息。它只是不会绑定一个复杂的对象。
| 归档时间: |
|
| 查看次数: |
9256 次 |
| 最近记录: |