Configuration Files and Other Configuration Sources

The default ASP.NET Core project template contains an “appsettings.json” file where we can place application configuration information. This includes connection strings, email server settings, UI settings like the page length for paged results, the number of pages shown in a pager, and so on.

However, appsettings.json is not the only source of configuration data. Configuration data can be retrieved from several .json and .xml files, from environment variables. Sensitive data, such as credentials and passwords can also be stored in encrypted sources.

Before describing the sources and how configuration data is available from inside the application, we need to learn how configuration data is organized in each configuration source, and how it is combined into a unique source of information.

Configuration data organization

Configuration data is organized in a tree-like fashion where each leaf may contain a number, a Boolean, a string, or an array of these simple values. The values of a non-leaf node can be arrays of branches.

In other words, configuration data is stored in JSON objects, and JSON files are the more adequate way to represent and set it.

Once in the application, data can be accessed through the IConfiguration interface that is available in the dependency injection engine. IConfiguration has a string indexer. Each leaf value can be accessed by passing a string indexer to IConfiguration. The string indexer is composed of all property names encountered in the path to the leaf value separated by colons, as shown below:

string town = Configuration["applicationOwner:address:town"]

The [] accessor returns the leaf JSON value as a string. The path passed to the indexer can also include the positions in JSON arrays. Thus, suppose configuration has the JSON structure below:

Get hands-on with 1400+ tech skills courses.