ASP .NET Core Get Json Array using IConfiguration

In appsettings.json

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

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").AsEnumerable());
}
}

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();

or like

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

相关链接

 评论


Copyright © 2019 、天上有木月博客 All Rights Reserved. by igeekfan. | 苏ICP备16046457号 | 本站运行于

本站开源 天上有木月 至Github , 总访问量为 次 。 载入天数...载入时分秒...