如何将 IConfigurationSection 中的配置映射到一个简单的类

Rob*_*abe 10 c# asp.net-mvc asp.net-web-api .net-core

使用 MVC .net Core 并在启动类中构建一个具体的配置类。我的 appsettings.json 看起来像这样:

{
  "myconfig": {
    "other2": "tester,
    "other": "tester",
    "root": {
      "inner": {
        "someprop": "TEST VALUE"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我用一个具体的类来表示这一点,如下所示:

public class TestConfig
{
    public string other2 { get; set; }
    public string other { get; set; }
    public Inner1 root { get; set; }
}

public class Inner1
{
    public Inner2 inner { get; set; }
}

public class Inner2
{
    public string someprop { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以通过执行以下操作轻松映射:

var testConfig = config.GetSection("myconfig").Get<TestConfig>();
Run Code Online (Sandbox Code Playgroud)

但是......我不喜欢上面的内容是需要使 TestConfig 比它需要的更复杂。理想情况下,我想要这样的东西:

public class PreciseConfig
{
    [Attribute("root:inner:someprop")]
    public string someprop { get; set; }
    public string other { get; set; }
    public string other2 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我不必在其中包含嵌套对象,并且可以以这种方式直接映射到较低的属性。这可能吗?使用 .net 核心 2.1。

提前感谢您的任何指点!

Ps 我知道我可以自己创建一个 PreciseConfig 实例并使用设置属性config.GetValue<string>("root:inner:someprop")但是如果我可以使用序列化属性或类似属性自动设置我不想以这种方式设置我的所有自定义设置。

Nko*_*osi 14

对于更高级别的配置,您可以像平常一样使用顶级节点获得配置。

然后使用路径从上一步myconfig:root:inner获取其他所需的部分和绑定PreciseConfig

var preciseConfig = config.GetSection("myconfig").Get<PreciseConfig>();

config.GetSection("myconfig:root:inner").Bind(preciseConfig);
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core 中的参考配置:GetSection

ASP.NET Core 中的参考配置:绑定到对象图