【问题标题】:How do I bind a multi level configuration object using IConfiguration in a .net Core application?如何在 .net Core 应用程序中使用 IConfiguration 绑定多级配置对象?
【发布时间】: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 正确地具有 IntervalCount,其值分别设置为 30 和 10。

但这不是:

Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();

mySettings 有一个空的foo

令人沮丧的是,如果我使用调试器,我可以看到从 appsettings.json 文件中读取了必要的数据 。我可以进入Configuration =&gt; Non-Public Members =&gt; _providers =&gt; [0] =&gt; Data 并查看我需要的所有信息。它只是不会绑定复杂的对象。

【问题讨论】:

  • 你的设置类是什么样子的?
  • FooSettings 是如何定义的?
  • @haim770 我已经添加了类定义。
  • 您的设置属性是myFoo,但您的设置是“Foo”...

标签: c# json asp.net-core .net-core


【解决方案1】:

您的属性必须与“appsettings.json”中的属性名称匹配。

您必须将设置的 myFoo 属性重命名为 Foo,因为这是 json 文件中的属性名称。

【讨论】:

  • 看起来这就是问题所在。我最终将属性命名为与对象相同的名称,以尽量减少混淆。现在我只需要获取字典(上面没有提到)映射。谢谢。
【解决方案2】:

您还可以使用 JsonProperty(Included in Newtonsoft.Json) 注解来告诉序列化程序该做什么,如下所示。

public class Settings
{
  [JsonProperty("Foo")]
  public Foo myFoo {get;set;}
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2017-08-21
  • 1970-01-01
相关资源
最近更新 更多