ASP.NET Core使用IConfiguration获取Json数组 [英] ASP.NET Core Get Json Array using IConfiguration

查看:1135
本文介绍了ASP.NET Core使用IConfiguration获取Json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在appsettings.json中

In appsettings.json

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


在Startup.cs


In Startup.cs

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


在HomeController中


In HomeController

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

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


上面有我的代码,我为空 如何获得数组?


There are my codes above, I got null How to get the array?

推荐答案

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

If you want to pick value of first item then you should do like this-

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

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

If you want to pick value of entire array then you should do like this-

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

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

Ideally, you should consider using options pattern suggested by official documentation. This will give you more benefits.

这篇关于ASP.NET Core使用IConfiguration获取Json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆