gpt4 book ai didi

来自 appsettings 的 C# 强类型 ConfigurationBuilder List
转载 作者:行者123 更新时间:2023-12-05 01:36:06 35 4
gpt4 key购买 nike

真的很纠结这个 - 有这么难吗?!

我的应用程序设置中有一个简单的对象数组:

"AppSettings": {
"Names": [
{
"Id": "1",
"Name": "Mike"
},
{
"Id": "2",
"Name": "John"
}
]
}

我要上课了

public class AppSettings
{
public List<Names> Names { get; set; } = new List<Names>();
}

public class Names
{
public string Id { get; set; }
public string Name { get; set; }
}

我在我的应用设置中阅读:

var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json").Build();

var config = new AppSettings();

这是错误的地方:

config.Names = configuration.GetSection("AppSettings:Names") //<<<< what do I do here?

它似乎都与 IConfigurationSection 相关联,但没有帮助。

最佳答案

使用 ConfigurationBinder.Get<T> 从设置中获取整个对象图扩展名。

ConfigurationBinder.Get<T> binds and returns the specified type. ConfigurationBinder.Get<T> may be more convenient than using ConfigurationBinder.Bind. The following code shows how to use ConfigurationBinder.Get<T> with the AppSettings class:

//...

AppSettings config = configuration.GetSection("AppSettings").Get<AppSettings>();

//...

引用 Configuration in ASP.NET Core

关于来自 appsettings 的 C# 强类型 ConfigurationBuilder List<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62302837/

35 4 0