ASP.NET Core Configuration Section in Startup

Updated Answer
For ASP Core 1.1.0 generic model binding is now done using Get:

var config = Configuration.GetSection("configuredClients").Get<ClientConfiguration>();

Original Answer
How about this:

var config = Configuration.GetSection("configuredClients").Bind<ClientConfiguration>();

With ASP.NET Core 2.0 (basically Core 1.1+), the IConfiguration is injected to Startup, and that can be used within ConfigureServices() and Configure() methods.

As shown in the accepted answer, the configuration can be bound to an object. But if just one value is required, the key based approach works well.

The IConfiguration still works with colon : separated string keys. And for array, use 0-based index. Or use the the generic getValue<T>() method with same keys. See example below:

var clientId2 = Configuration["configuredClients:clients:1:clientId"]?.ToString();
var clientName1 = Configuration.GetValue<string>("configuredClients:clients:0:clientName");

To use the same configuration values in other classes (e.g. Controllers)

  1. Either inject the IConfiguration and use the same key-based approach like above. Or
  2. Register an instance of the strongly-typed configuration object with the DI container, and inject that object directly into client classes.

Sample code below:

//In Startup.ConfigureServices()
var clientConfig = Configuration.GetSection("configuredClients")
    .Get<ClientConfiguration>();
services.AddSingleton(clientConfig);

//Controller
public class TestController : Controller
{
    IConfiguration _configStore;
    ClientConfiguration _clientConfiguration;

    public TestController(IConfiguration configuration, 
        ClientConfiguration clientConfiguration)
    {
        _configStore = configuration;
        _clientConfiguration = clientConfiguration;
    }

    public IActionResult Get()
    {
        //with IConfiguration
        var clientId1 = _configStore
            .GetValue<string>("configuredClients:clients:0:clientId");

        //with strongly typed ClientConfiguration
        var clientName1 = _clientConfiguration.Clients[0]?.ClientName;

        return new OkObjectResult("Configuration test");
    }
}

More examples here.


You don't read the configuration manually generally in ASP.NET Core yourself, instead you create an object that matches your definition. You can read more on that in the official documentation here.

E.g.

public class MyOptions
{
    public string Option1 { get; set; }
    public int Option2 { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{
    // Setup options with DI
    services.AddOptions();
    services.Configure<MyOptions>(Configuration);
}

Then you just inject the options IOptions<MyOptions> where you need them.