gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 18:21:20 26 4
gpt4 key购买 nike

使用 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 核心 2.1。

感谢您提前提供任何指示!

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

最佳答案

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

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

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

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

引用 Configuration in ASP.NET Core : GetSection

引用 Configuration in ASP.NET Core : Bind to an object graph

关于c# - 如何将 IConfigurationSection 中的配置映射到一个简单的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519150/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com