ASP.NET Core使用IConfiguration获取Json数组


167

在appsettings.json中

{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}

在Startup.cs中

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}

在HomeController中

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    public HomeController(IConfiguration config)
    {
        this._config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}

上面有我的代码,我为null如何获取数组?

Answers:


102

如果您想选择第一项的价值,则应该这样做-

var item0 = _config.GetSection("MyArray:0");

如果您想选择整个数组的值,则应该这样做-

IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();

理想情况下,您应该考虑使用官方文档建议的选项模式。这将为您带来更多好处。


23
如果您有类似的对象数组"Clients": [ {..}, {..} ],则应调用Configuration.GetSection("Clients").GetChildren()
halllo

39
如果您有多个类似的文字"Clients": [ "", "", "" ],则应调用.GetSection("Clients").GetChildren().ToArray().Select(c => c.Value).ToArray()
halllo

6
这个答案实际上将产生4个项目,第一个是具有空值的section本身。不正确
Giovanni Bassi '18

4
我成功地这样调用了它:var clients = Configuration.GetSection("Clients").GetChildren() .Select(clientConfig => new Client { ClientId = clientConfig["ClientId"], ClientName = clientConfig["ClientName"], ... }) .ToArray();
halllo

1
这些选项对我都不起作用,因为使用hallo的示例,对象在“客户端”处返回null。我相信json格式正确,因为它可以插入格式为[Item]:[{...},{...}]的字符串[“ item:0:childItem”]中的偏移量
Clarence

280

您可以安装以下两个NuGet软件包:

Microsoft.Extensions.Configuration    
Microsoft.Extensions.Configuration.Binder

然后,您将可以使用以下扩展方法:

var myArray = _config.GetSection("MyArray").Get<string[]>();

13
这比其他答案要简单得多。
jao

14
到目前为止,这是最好的答案。
Giovanni Bassi '18

14
就我而言,Aspnet核心2.1 Web应用程序包括这两个nuget程序包。所以这只是一线变更。谢谢
Shibu Thannikkunnath 18/09/27

最简单的一个!
Pablo

3
它还可以处理对象数组,例如 _config.GetSection("AppUser").Get<AppUser[]>();
Giorgos Betsos

60

在您的appsettings.json中添加一个级别:

{
  "MySettings": {
    "MyArray": [
      "str1",
      "str2",
      "str3"
    ]
  }
}

创建一个代表您的部分的类:

public class MySettings
{
     public List<string> MyArray {get; set;}
}

在应用程序启动类中,将模型绑定并注入到DI服务中:

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));

在您的控制器中,从DI服务获取您的配置数据:

public class HomeController : Controller
{
    private readonly List<string> _myArray;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _myArray = mySettings.Value.MyArray;
    }

    public IActionResult Index()
    {
        return Json(_myArray);
    }
}

如果需要所有数据,还可以将整个配置模型存储在控制器的属性中:

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

    public HomeController(IOptions<MySettings> mySettings)
    {
        _mySettings = mySettings.Value;
    }

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}

ASP.NET Core的依赖项注入服务的工作原理很简单:)


那么如何MySettings在启动中使用?
T.Coutlakis

我收到一个错误,它需要在“ MySettings”和“ MyArray”之间加逗号。
Markus

35

如果您有像这样的复杂JSON对象数组:

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}

您可以通过以下方式检索设置:

var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}

30

这对我来说可以从配置中返回字符串数组:

var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
    .Get<string[]>();

我的配置部分如下所示:

"AppSettings": {
    "CORS-Settings": {
        "Allow-Origins": [ "http://localhost:8000" ],
        "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
    }
}

15

对于从配置中返回复杂的JSON对象数组的情况,我已将@djangojazz的答案改编为使用匿名类型和动态而不是元组。

给定设置部分:

"TestUsers": [
{
  "UserName": "TestUser",
  "Email": "Test@place.com",
  "Password": "P@ssw0rd!"
},
{
  "UserName": "TestUser2",
  "Email": "Test2@place.com",
  "Password": "P@ssw0rd!"
}],

您可以通过以下方式返回对象数组:

public dynamic GetTestUsers()
{
    var testUsers = Configuration.GetSection("TestUsers")
                    .GetChildren()
                    .ToList()
                    .Select(x => new {
                        UserName = x.GetValue<string>("UserName"),
                        Email = x.GetValue<string>("Email"),
                        Password = x.GetValue<string>("Password")
                    });

    return new { Data = testUsers };
}

这太棒了
Vladimir Demirev '19

11

有点老问题了,但是我可以为使用C#7标准的.NET Core 2.1提供更新的答案。说我仅在appsettings.Development.json中有一个列表,例如:

"TestUsers": [
  {
    "UserName": "TestUser",
    "Email": "Test@place.com",
    "Password": "P@ssw0rd!"
  },
  {
    "UserName": "TestUser2",
    "Email": "Test2@place.com",
    "Password": "P@ssw0rd!"
  }
]

我可以将它们提取到实现并连接了Microsoft.Extensions.Configuration.IConfiguration的任何位置,如下所示:

var testUsers = Configuration.GetSection("TestUsers")
   .GetChildren()
   .ToList()
    //Named tuple returns, new in C# 7
   .Select(x => 
         (
          x.GetValue<string>("UserName"), 
          x.GetValue<string>("Email"), 
          x.GetValue<string>("Password")
          )
    )
    .ToList<(string UserName, string Email, string Password)>();

现在,我有一个类型正确的对象的列表。如果我进入testUsers.First(),Visual Studio现在应该显示“用户名”,“电子邮件”和“密码”的选项。


9

在ASP.NET Core 2.2和更高版本中,我们可以像您的情况一样在应用程序中的任何位置注入IConfiguration,您可以在HomeController中注入IConfiguration并以此方式获取数组。

string[] array = _config.GetSection("MyArray").Get<string[]>();


4

简写:

var myArray= configuration.GetSection("MyArray")
                        .AsEnumerable()
                        .Where(p => p.Value != null)
                        .Select(p => p.Value)
                        .ToArray();

它返回一个字符串数组:

{“ str1”,“ str2”,“ str3”}


1
为我工作。谢谢。使用Microsoft.Extensions.Configuration.Binder也 可以使用,但是如果单行代码可以完成此工作,我想避免引用另一个Nuget程序包。
Sau001,19年

3

这对我有用;创建一些json文件:

{
    "keyGroups": [
        {
            "Name": "group1",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature2And3",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature5Group",
            "keys": [
                "user5"
            ]
        }
    ]
}

然后,定义一些映射的类:

public class KeyGroup
{
    public string name { get; set; }
    public List<String> keys { get; set; }
}

nuget包:

Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3

然后,加载它:

using Microsoft.Extensions.Configuration;
using System.Linq;
using System.Collections.Generic;

ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

configurationBuilder.AddJsonFile("keygroup.json", optional: true, reloadOnChange: true);

IConfigurationRoot config = configurationBuilder.Build();

var sectionKeyGroups = 
config.GetSection("keyGroups");
List<KeyGroup> keyGroups = 
sectionKeyGroups.Get<List<KeyGroup>>();

Dictionary<String, KeyGroup> dict = 
            keyGroups = keyGroups.ToDictionary(kg => kg.name, kg => kg);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.