ASP.NET Core Get Json Array using IConfiguration
You can install the following two NuGet packages:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Binder;
And then you'll have the possibility to use the following extension method:
var myArray = _config.GetSection("MyArray").Get<string[]>();
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.
Add a level in your appsettings.json :
{
"MySettings": {
"MyArray": [
"str1",
"str2",
"str3"
]
}
}
Create a class representing your section :
public class MySettings
{
public List<string> MyArray {get; set;}
}
In your application startup class, bind your model an inject it in the DI service :
services.Configure<MySettings>(options => Configuration.GetSection("MySettings").Bind(options));
And in your controller, get your configuration data from the DI service :
public class HomeController : Controller
{
private readonly List<string> _myArray;
public HomeController(IOptions<MySettings> mySettings)
{
_myArray = mySettings.Value.MyArray;
}
public IActionResult Index()
{
return Json(_myArray);
}
}
You can also store your entire configuration model in a property in your controller, if you need all the data :
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptions<MySettings> mySettings)
{
_mySettings = mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.MyArray);
}
}
The ASP.NET Core's dependency injection service works just like a charm :)
If you have array of complex JSON objects like this:
{
"MySettings": {
"MyValues": [
{ "Key": "Key1", "Value": "Value1" },
{ "Key": "Key2", "Value": "Value2" }
]
}
}
You can retrieve settings this way:
var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
var key = section.GetValue<string>("Key");
var value = section.GetValue<string>("Value");
}
This worked for me to return an array of strings from my config:
var allowedMethods = Configuration.GetSection("AppSettings:CORS-Settings:Allow-Methods")
.Get<string[]>();
My configuration section looks like this:
"AppSettings": {
"CORS-Settings": {
"Allow-Origins": [ "http://localhost:8000" ],
"Allow-Methods": [ "OPTIONS","GET","HEAD","POST","PUT","DELETE" ]
}
}