Organize your configuration settings into a hierarchical structure using JSON, XML, or INI files. This hierarchical structure allows you to group related settings under sections and subsections, making your configuration more readable, maintainable, and scalable.
JSON-Based Hierarchical Configuration (appsettings.json): { “ConnectionStrings”: { “DefaultConnection”: “Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;” }, “Logging”: { “LogLevel”: { “Default”: “Information”, “Microsoft.AspNetCore”: “Warning” } }, “Inventory”: { “StockAlertThreshold”: 20, “WarehouseLocations”: [ “New York”, “London”, “Tokyo” ] } } In this example: Sections: The top-level keys (ConnectionStrings, Logging, Inventory) define sections within the configuration. Nested Sections: The Logging section further contains a nested LogLevel section. Arrays: The WarehouseLocations setting is an array of strings within the Inventory section.
Accessing Hierarchical Configuration with IConfiguration The IConfiguration interface provides methods to easily navigate and retrieve values from this hierarchical structure. GetSection(string key): Returns an IConfigurationSection object representing the specified section. Use this to drill down into nested sections. GetValue<T>(string key): Retrieves a configuration value as the specified type T. The key can include the entire path to the value, using colons (:) to separate sections. Indexer (this[string key]): Retrieves a configuration value as a string. Works like the GetValue<string>() method.
Code Examples var connectionString = _configuration.GetConnectionString(“DefaultConnection”);
var logLevel = _configuration.GetValue<string>(“Logging:LogLevel:Default”);
// Using IConfigurationSection: var inventorySection = _configuration.GetSection(“Inventory”); var stockAlertThreshold = inventorySection.GetValue<int>(“StockAlertThreshold”);
// Get an array var warehouseLocations = inventorySection.GetSection(“WarehouseLocations”).Get<string[]>();