如何将appsettings数组转换为只读集合



我正试图从我的应用程序设置中获得以下内容:

"ApiKeys": {
"Keys": [
{
"Key": "06795D9D-A770-44B9-9B27-03C6ABDB1BAE",
"Roles": [ "Manager" ]
}
]
}

我正在使用以下内容:

public class ApiKey
{
public ApiKey(string key, IReadOnlyCollection<string> roles)
{
Key = key ?? throw new ArgumentNullException(nameof(key));
Roles = roles ?? throw new ArgumentNullException(nameof(roles));
}
public string Key { get; }
public IReadOnlyCollection<string> Roles { get; }
}

代码中的其他地方。。。。。。。。。。。。。。。。。。。。。。

_config.GetSection("ApiKeys:Keys").Get<List<ApiKey>>();

当我把角色作为标准的"列表",但我真的希望它作为"ReadOnlyCollection"时,它就起作用了。

有什么建议吗?

var settings = _config.GetSection("ApiKeys:Keys").Get<List<ApiKey>>();
return new ReadOnlyCollection<ApiKey>(settings);

据我所知,绑定到一个类型需要一个带有默认构造函数的类型,因为绑定器将使用Activator.CreateInstance来创建它绑定到的实例。所以你不能有这样的构造函数。

此外,绑定器显式跳过任何没有setter的属性,因此您不能拥有只读属性并期望绑定器工作。

代码没有失败的唯一原因是绑定到List<ApiKey>,因此ApiKey绑定的失败会被简单地接受。

如果您更改类型,使其具有默认的构造函数和setter,那么绑定到它将起作用,即使使用只读集合也是如此。

public class ApiKey
{
public string Key { get; set; }
public IReadOnlyCollection<string> Roles { get; set; }
}

如果您不希望ApiKey类型以后是可变的,请考虑在从配置绑定后将其转换为另一个只读类型。

请注意,在相关选项模式的上下文中,通常需要可变选项类型,因为它们可以从多个源进行配置(例如,从配置,然后从配置操作,甚至可能使用配置后操作(。

最新更新