本文介绍了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);
}

在家庭控制器中


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 nullHow 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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 10:12