简体   繁体   English

绑定来自 appsettings.json 的字符串列表

[英]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.

相关问题 如何从 appsettings.json 读取列表并将其绑定到 mvc dropdownlistfor() - How to read a list from appsettings.json and bind it in the mvc dropdownlistfor() 如何从 .net core 中的 appsettings.json 中提取列表 - How to extract a list from appsettings.json in .net core 无法从appsettings.json获取连接字符串 - Cannot get connection string from appsettings.json 使用从appsettings.json到startup.cs的连接字符串 - Using connection string from appsettings.json to startup.cs .Net Core Cant从appsettings.json中读取连接字符串 - .Net Core Cant read connection string from appsettings.json .NET Core从appsettings.json获取连接字符串 - .NET Core get connection string from appsettings.json 如何从 DotNetCore 2.2 中的 appsettings.json 读取连接字符串? - How to read connection string from appsettings.json in DotNetCore 2.2? 由于 appsettings.json 的路径,add-migration 无法从文件 appsettings.json 读取连接字符串 - add-migration can not read the connection string from the file appsettings.json because of the path to appsettings.json 将appsettings.json部分绑定到POCO列表 - Binding an appsettings.json section to a list of POCO 如何使用值列表读取 appsettings.json? - How to read appsettings.json with List of values?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM