[英]Bind list of string from appsettings.json
I have the following list of string defined in my appSettings我的 appSettings 中定义了以下字符串列表
"AllowedGroups": [ "support", "admin", "dev" ]
and I want to bind it to a class in the startup for dependency injection.我想在启动时将它绑定到 class 以进行依赖注入。
This is my model class这是我的 model class
public class AllowedGroups
{
public List<string> Groups { get; set; }
}
This is how I tried to bind it.这就是我尝试绑定它的方式。
services.Configure<AllowedGroups>(Configuration.GetSection("AllowedGroups"));
I would like to keep the appsettings file in this format and I don't know how should I define de model class accordingly and how to bind it.我想以这种格式保存 appsettings 文件,但我不知道我应该如何相应地定义 de model class 以及如何绑定它。 I'm aware that he might expect to have
"AllowedGroups":{Groups: [ "support", "admin", "dev" ]}
with the current model我知道他可能希望在当前 model 中拥有
"AllowedGroups":{Groups: [ "support", "admin", "dev" ]}
If you want to keep config structure you can just resolve everything "raw":如果你想保持配置结构,你可以解决一切“原始”:
var allowedGroups = Configuration.GetSection("AllowedGroups").Get<List<string>>();
services.AddSingleton(new AllowedGroups {Groups = allowedGroups});
Note that this will just register the AllowedGroups
not the options as Configure
does.请注意,这只会注册
AllowedGroups
而不是像Configure
那样注册选项。 TO register options you can use next overload of Configure
:要注册选项,您可以使用
Configure
的下一个重载:
services.Configure<AllowedGroups>(allowedGroups =>
allowedGroups.Groups = Configuration.GetSection("AllowedGroups").Get<List<string>>());
You can do this:你可以这样做:
_config.GetConfigSection("AllowedGroups").GetChildren().ToList();
_config being derived from IConfiguration. _config 派生自 IConfiguration。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.