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

问题描述 投票:0回答:1

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

{
    "myconfig": {
        "other2": "tester",
        "other": "tester",
        "root": {
            "inner": {
                "someprop": "TEST VALUE"
            }
        }
    }
}

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

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; }
}

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

var testConfig = config.GetSection("myconfig").Get<TestConfig>();

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

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

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

提前感谢您的指点!

P.s.我知道我可以自己创建一个 PreciseConfig 实例并使用

config.GetValue<string>("root:inner:someprop")
设置属性,但如果我可以使用序列化属性或类似属性自动执行这些设置,我不想以这种方式设置所有自定义设置。

c# asp.net-mvc asp.net-web-api .net-core
1个回答
31
投票

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

然后使用路径

myconfig:root:inner
获取其他所需部分并从上一步绑定
PreciseConfig

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

config.GetSection("myconfig:root:inner").Bind(preciseConfig);

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

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

© www.soinside.com 2019 - 2024. All rights reserved.