【问题标题】:Binding Configurations to a Complex Object将配置绑定到复杂对象
【发布时间】:2021-10-06 09:11:09
【问题描述】:

在 ASP.NET Core 2.2 中,我尝试将 JSON 对象数组绑定到匹配的 C# 对象,但它没有正确绑定成员。 (剧透:Test1 有效,Test2 无效。)

在我的 appsettings.json 中,我有这个配置:

{
    "Test1": [
        "A",
        "B",
        "C"
    ],
    "Test2": [
        { "s": "A" },
        { "s": "B" },
        { "s": "C" }
    ]
}

这是以一种非常标准的方式被拉入 Program 类中的 Configuration 对象的,这对我来说对于所有其他目的都很好。

public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json",optional: false, reloadOnChange: true)
   .AddEnvironmentVariables()
   .Build();

在我的程序中,我创建了一个与 Test2 数组中的对象匹配的类。

public class Test2Class
{
    public string s;
}

最后,我像这样绑定它们:

List<string> test1 = new List<string>();
Program.Configuration.Bind("Test1", test1);
List<TestClass> test2 = new List<TestClass>();
Program.Configuration.Bind("Test2", test2);

当我检查结果时,我得到的是:

test1 = ["A", "B", "C"]
test2 = [{s: null}, {s: null}, {s: null}]

为了正确绑定 Test2 数组,我需要做些什么不同的事情?

【问题讨论】:

  • TestClass.s 应该是一个属性而不是一个字段

标签: json asp.net-core-2.2 appsettings c#-7.0


【解决方案1】:

TestClass.s 应该是一个属性,而不是一个字段

public class TestClass {
    public string s { get; set; }
}

下面的例子也可以用来更方便的获取想要的类型

List<string> test1 = Program.Configuration.GetSection("Test1").Get<List<string>>();
List<TestClass> test2 = Program.Configuration.GetSection("Test2").Get<List<TestClass>>();

参考Bind hierarchical configuration data using the options pattern

【讨论】:

  • 天啊!谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 2011-08-22
  • 2013-05-29
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多