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 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.