IConfiguration is the .NET abstraction for reading the combined key-value settings supplied by configuration providers such as JSON files, environment variables, and command-line arguments. section 10.2
ASP.NET Core commonly exposes it through dependency injection, so endpoint handlers and application classes can read settings without knowing which provider supplied them. Use the indexer for keys such as Configuration["MapSettings:DefaultZoomLevel"]. section 10.2.1 section 10.5
Keep these configuration behaviors in mind:
- Nested settings use colon-separated keys, such as MapSettings:DefaultLocation:Latitude. section 10.2.1
- Later providers override values from earlier providers while preserving keys that exist only in earlier sources. section 10.5
- WebApplicationBuilder configures common providers automatically, while ConfigurationManager can accept additional providers or replace the defaults. section 10.2.1 section 10.5
Reading a map setting
A JSON setting such as MapSettings:DefaultZoomLevel can be read with builder.Configuration["MapSettings:DefaultZoomLevel"]. The same IConfiguration value can be injected into an endpoint handler. section 10.2.1
Listing 10.3 Loading appsettings.json by clearing the configuration sources
WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Configuration.Sources.Clear(); #1 builder.Configuration.AddJsonFile("appsettings.json", optional: true); #2 WebApplication app = builder.Build(); app.MapGet("/", () => app.Configuration.AsEnumerable()); #3 app.Run(); #1 Clears the providers configured by default in WebApplicationBuilder #2 Adds a JSON configuration provider, providing the name of the configuration file #3 Returns all the configuration key-value pairs for display purposes
Shows how to clear the default providers, add an optional JSON file, and return the resulting key-value pairs. section 10.2.1
