来自 appsettings 的 C# 强类型 ConfigurationBuilder List<object>
C# strongly typed ConfigurationBuilder List<object> from appsettings
真的很纠结这个 - 有这么难吗?!
我的应用程序设置中有一个简单的对象数组:
"AppSettings": {
"Names": [
{
"Id": "1",
"Name": "Mike"
},
{
"Id": "2",
"Name": "John"
}
]
}
然后我有一个class
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>();
//...
真的很纠结这个 - 有这么难吗?!
我的应用程序设置中有一个简单的对象数组:
"AppSettings": {
"Names": [
{
"Id": "1",
"Name": "Mike"
},
{
"Id": "2",
"Name": "John"
}
]
}
然后我有一个class
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 usingConfigurationBinder.Bind
. The following code shows how to useConfigurationBinder.Get<T>
with theAppSettings
class:
//...
AppSettings config = configuration.GetSection("AppSettings").Get<AppSettings>();
//...