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

Gar*_*ary 127 c# asp.net-core-mvc asp.net-core

在appsettings.json中

{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}
Run Code Online (Sandbox Code Playgroud)

在Startup.cs中

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton<IConfiguration>(Configuration);
}
Run Code Online (Sandbox Code Playgroud)

在HomeController中

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

    public IActionResult Index()
    {
        return Json(_config.GetSection("MyArray"));
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Raz*_*tru 215

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

Microsoft.Extensions.Configuration    
Microsoft.Extensions.Configuration.Binder
Run Code Online (Sandbox Code Playgroud)

然后你就可以使用以下扩展方法:

var myArray = _config.GetSection("MyArray").Get<string[]>();
Run Code Online (Sandbox Code Playgroud)

  • 到目前为止,这是最好的答案. (12认同)
  • 在我的例子中,Aspnet核心2.1网络应用程序,包括这两个nuget包.所以这只是一个换线.谢谢 (11认同)
  • 这比其他答案简单得多. (10认同)
  • 它还适用于对象数组,例如 `_config.GetSection("AppUser").Get&lt;AppUser[]&gt;();` (8认同)
  • 我想知道为什么他们不能通过简单地使用 `GetValue` 作为该键来使其工作:`Configuration.GetValue&lt;string[]&gt;("MyArray")`。 (4认同)
  • 推荐用于说明所需的程序集。 (2认同)
  • 最简单的一个! (2认同)

San*_*ket 75

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

var item0 = _config.GetSection("MyArray:0");
Run Code Online (Sandbox Code Playgroud)

如果你想挑选整个阵列的价值,你应该这样做 -

IConfigurationSection myArraySection = _config.GetSection("MyArray");
var itemArray = myArraySection.AsEnumerable();
Run Code Online (Sandbox Code Playgroud)

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

  • 如果你有像"客户端"这样的文字数组:["","",""]`,你应该调用`.GetSection("Clients").GetChildren().ToArray().选择(c => c.Value).ToArray()`. (18认同)
  • 如果你有一个像"客户端"这样的对象数组:[{..},{..}]`,你应该调用`Configuration.GetSection("Clients").GetChildren()`. (14认同)
  • 这个答案实际上将产生4个项目,第一个是具有空值的section本身。不正确 (4认同)
  • 我像这样成功地调用了它:`var clients = Configuration.GetSection(“ Clients”)。GetChildren().Select(clientConfig =&gt; new Client {ClientId = clientConfig [“ ClientId”],ClientName = clientConfig [“ ClientName”], ...}).ToArray();` (3认同)
  • 这些选项都不适合我,因为使用 Hallo 的示例,对象在“客户端”点返回 null。我相信 json 的格式良好,因为它与以“Item”:[{...},{...}] 格式插入字符串 ["item:0:childItem"] 中的偏移量一起工作 (3认同)

Adr*_*ris 51

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

{
  "MySettings": {
    "MyArray": [
      "str1",
      "str2",
      "str3"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

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

public class MySettings
{
     public List<string> MyArray {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

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

services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
Run Code Online (Sandbox Code Playgroud)

在您的控制器中,从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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public class HomeController : Controller
{
    private readonly MySettings _mySettings;

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

    public IActionResult Index()
    {
        return Json(_mySettings.MyArray);
    }
}
Run Code Online (Sandbox Code Playgroud)

ASP.NET Core的依赖注入服务就像一个魅力:)

  • 这应该是公认的答案。做得好。 (3认同)

Dmi*_*lov 26

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

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 正是我想要的,太棒了! (3认同)
  • 正是我一直在寻找的东西,非常有效,谢谢! (2认同)
  • 简单明了! (2认同)

Cod*_*ief 21

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

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

我的配置部分如下所示:

"AppSettings": {
    "CORS-Settings": {
        "Allow-Origins": [ "http://localhost:8000" ],
        "Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
    }
}
Run Code Online (Sandbox Code Playgroud)


Bja*_*i B 11

点网核心 3.1:

json配置:

"TestUsers": 
{
    "User": [
    {
      "UserName": "TestUser",
      "Email": "Test@place.com",
      "Password": "P@ssw0rd!"
    },
    {
      "UserName": "TestUser2",
      "Email": "Test2@place.com",
      "Password": "P@ssw0rd!"
    }]
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个 User.cs 类,该类具有与上面 Json 配置中的 User 对象相对应的自动属性。然后您可以参考 Microsoft.Extensions.Configuration.Abstractions 并执行以下操作:

List<User> myTestUsers = Config.GetSection("TestUsers").GetSection("User").Get<List<User>>();
Run Code Online (Sandbox Code Playgroud)


jay*_*cer 10

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

给定设置部分:

"TestUsers": [
{
  "UserName": "TestUser",
  "Email": "Test@place.com",
  "Password": "P@ssw0rd!"
},
{
  "UserName": "TestUser2",
  "Email": "Test2@place.com",
  "Password": "P@ssw0rd!"
}],
Run Code Online (Sandbox Code Playgroud)

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

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 };
}
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以直接获取数组,而无需在配置中增加新级别:

public void ConfigureServices(IServiceCollection services) {
    services.Configure<List<String>>(Configuration.GetSection("MyArray"));
    //...
}
Run Code Online (Sandbox Code Playgroud)


dja*_*azz 6

有点老问题了,但是我可以为使用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!"
}
Run Code Online (Sandbox Code Playgroud)

],

我可以将它们提取到实现并连接了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)>();
Run Code Online (Sandbox Code Playgroud)

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


Rol*_*oos 6

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

{
    "keyGroups": [
        {
            "Name": "group1",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature2And3",
            "keys": [
                "user3",
                "user4"
            ]
        },
        {
            "Name": "feature5Group",
            "keys": [
                "user5"
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

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

public class KeyGroup
{
    public string name { get; set; }
    public List<String> keys { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

nuget 包:

Microsoft.Extentions.Configuration.Binder 3.1.3
Microsoft.Extentions.Configuration 3.1.3
Microsoft.Extentions.Configuration.json 3.1.3
Run Code Online (Sandbox Code Playgroud)

然后,加载它:

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);
Run Code Online (Sandbox Code Playgroud)


moj*_*imi 5

简写:

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

它返回一个字符串数组:

{"str1","str2","str3"}

  • 为我工作。谢谢。使用 **Microsoft.Extensions.Configuration.Binder** 也可以,但是如果一行代码可以完成这项工作,我想远离引用另一个 Nuget 包。 (2认同)

san*_*ndy 5

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

string[] array = _config.GetSection("MyArray").Get<string[]>();
Run Code Online (Sandbox Code Playgroud)


wor*_*dev 5

Microsoft.Extensions.Configuration.Binder您可以像这样使用包:

在你的appsettings.json

{
      "MyArray": [
          "str1",
          "str2",
          "str3"
      ]
}
Run Code Online (Sandbox Code Playgroud)

创建对象来保存您的配置:

 public class MyConfig
 {
     public List<string> MyArray { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

在你的控制器中Bind配置:

public class HomeController : Controller
{
    private readonly IConfiguration _config;
    private readonly MyConfig _myConfig = new MyConfig();

    public HomeController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Index()
    {
        return Json(_config.Bind(_myConfig));
    }
}
Run Code Online (Sandbox Code Playgroud)