2

I have array in my appsettings.json

"steps": [
{
  "name": "IMPORT",
  "enabled": true
},
{
  "name": "IMPORT_XML",
  "enabled": true
},
{
  "name": "COMPARE",
  "enabled": true
},
{
  "test_name": "COMPARE_TABLE",
  "enabled": true
}]

In my class I am trying to retrieve it using IConfigurationRoot _configurationRoot

I've tried:

var procSteps = _configurationRoot.GetSection("steps");
foreach (IConfigurationSection section in procSteps.GetChildren())
{
    var key = section.GetValue<string>("test");
    var value = section.GetValue<string>("enabled");
}

and:

var procSteps = _configurationRoot.GetSection("ExecutionSteps")
            .GetChildren()
            .Select(x => x.Value)
            .ToArray();

But none of them retrieved me values of it. Does anyone know what's the case and what is the correct way to access values of such array?

1 Answer 1

9

Create an object model to hold the values

public class ProcessStep {
    public string name { get; set; }
    public bool enabled { get; set; }
}

Then get the array from the section using Get<T>

ProcessStep[] procSteps = _configurationRoot
    .GetSection("steps")
    .Get<ProcessStep[]>();

ASP.NET Core 1.1 and higher can use Get<T>, which works with entire sections. Get<T> can be more convenient than using Bind

Reference Configuration in ASP.NET Core: Bind to an object graph

Sign up to request clarification or add additional context in comments.

2 Comments

I get the error: "IConfiguration/IConfigurationSection does not contain a definition for Get"
@zameb you are most likely missing a using reference for the extension method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.