Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从appsettings.json绑定字符串列表_C#_.net Core_Appsettings - Fatal编程技术网

C# 从appsettings.json绑定字符串列表

C# 从appsettings.json绑定字符串列表,c#,.net-core,appsettings,C#,.net Core,Appsettings,我在appSettings中定义了以下字符串列表 "AllowedGroups": [ "support", "admin", "dev" ] 我想将它绑定到启动中的一个类,以进行依赖项注入 这是我的模型课 public class AllowedGroups { public List<string> Groups { get; set; } } 公共类All

我在appSettings中定义了以下字符串列表

 "AllowedGroups": [ "support", "admin", "dev" ] 
我想将它绑定到启动中的一个类,以进行依赖项注入

这是我的模型课

  public class AllowedGroups
    {
        public List<string> Groups { get; set; }
    }
公共类AlloweGroup
{
公共列表组{get;set;}
}
这就是我试图捆绑它的方式

   services.Configure<AllowedGroups>(Configuration.GetSection("AllowedGroups"));
services.Configure(Configuration.GetSection(“alloweGroups”);
我想保持appsettings文件的这种格式,但我不知道应该如何相应地定义反模型类以及如何绑定它。 我知道他可能希望有
“AlloweGroups”:{Groups:[“support”,“admin”,“dev”]}
对于当前的模型

您可以这样做:

_config.GetConfigSection("AllowedGroups").GetChildren().ToList();

_配置是从IConfiguration派生的。

如果您想保留配置结构,只需将所有内容解析为“原始”:


如果希望JSON保持不变,则需要更改类或根据@Guru的答案手动构建它。尽管这一切都让人感觉有点不舒服,但我认为更改JSON是最明智的选择。
var allowedGroups = Configuration.GetSection("AllowedGroups").Get<List<string>>();
services.AddSingleton(new AllowedGroups {Groups = allowedGroups});
services.Configure<AllowedGroups>(allowedGroups =>
    allowedGroups.Groups = Configuration.GetSection("AllowedGroups").Get<List<string>>());