Configuration in ASP.NET Core

The Configuration system has gone through a lot of changes in new ASP.NET Core. The older ASP.NET used the Web.config file store configuration information. The newer configuration system now provides API to load the configuration from various sources like Json, XML, INI, Command line argument, Environment variables etc. In this tutorial, let us see how to store and retrieve the configuration from the appsettings.json file.

What is Configuration

The Configuration is the parameters or the initial settings specific to the application. These settings are stored separately from the code and in an external file.  This gives the developers and administrators control and flexibility over the way applications are run.

For example, the Connection Strings required to connect to the database is stored in a Configuration file. By Modifying the connection string you can change the database name, location etc without modifying the code.

The ASP.NET Applications used the Web.config to store the Configurations. For Example, the connection string is stored as shown below

Configuration in ASP.NET Core

The configuration in ASP.NET Core applications is stored in name-value pairs. You can store it in Json, XML or INI file formats. 

The example below is of simple configuration in Json format

The name-value pairs may be grouped into multi-level hierarchy as shown below

The ASP.NET Core Applications read the configuration files at startup. It can also be configured to read the configuration files during the runtime if it changes.

Configuration Sources

The ASP.NET Core allows us to read the configuration values from the various sources and file formats. Some of the commonly used sources are

  1. Files Format (Json, INI or XML)
  2. Command Line Arguments
  3. Environment Variables
  4. Custom Provider created by You

Now, let us look at how configurations are stored and retrieved in the ASP.NET Core.

Loading the Configuration

Open Visual Studio 2017 and create a new  ASP.NET Core 2.0 Empty project. If you are new to ASP.Net core, we recommend you to read the tutorial

Open program.cs. It has the Main method, which is the entry point to the application.  We discussed this in the tutorial application startup in ASP.NET Core

The Main method calls the CreateDefaultBuilder, which is a helper class. You can take a look at the source code from the GitHub.  

One of the tasks performed by the CreateDefaultBuilder is to load the configuration from various sources.

The code related to Configuring the application is here

ConfigureAppConfiguration 

The ConfigureAppConfiguration method takes two parameters.

First HostingContext an instance of WebHostBuilderContext and config which is an instance of IConfigurationBuilderWebHostBuilderContext  exposes the property HostingEnvironment, which lets us know whether we are running Development (isDevelopment), Production (IsProduction) or staging (IsStaging) environment

The IConfigurationBuilder exposes several methods to load the configuration file

Loading the Configuration from json file

The AddJsonFile Loads the configuration from the Json file.

The first argument is the name of the json file. The path is relative to the ContentRoot.

If the second parameter is optional. if it is set to true the AddJsonfile does not throw any errors if the appsettings.json file is not found.

The third parameter reloadOnChange if true, reloads the configuration if contents of the configuration file changes. There is no need to restart the application.

The next line of code loads the which matches the name appsettings.{env.EnvironmentName}.json This allows us to have different configuration files for each environment like appsetting.development.json, etc   

Loading the user secrets

This is a new feature in ASP.NET Core, where the configuration is stored outside the repository. It’s called user secrets and applicable only in Development environment.

Loading from the environment variables

The AddEnvironmentVariables reads all the user and system environment variables

Loading from command line arguments

The AddCommandLine loads all the command line arguments to the configuration

Reading the Configuration

The default Empty template does not create the appsetting.json file. Create the appsetting.json file the project root folder.

Add the following configuration. Note that Configuration keys are case-insensitive.

Now let us read the message property. Open the startup.cs

Import the namespace using Microsoft.Extensions.Configuration;

To read the configuration, we need an instance of IConfiguration. We can use the dependency injection to get the instance of it in the constructor of our startup class. You can use the same technique in the Controller class.

And then you can retrieve it using Configuration.getSection method

Reading the Connection string

The database Connection strings can be added as shown below.  The MySQL Connection & SQL Connection strings are grouped under ConnectionStrings section or node.

Each section or nodes are separated by a colon and the values are retrieved as follows. 

Reading Arrays in the Configure file

You can use Json formatted arrays like the one shown below

To read the above use an array index as part of the colon-separated string as shown below

Command line

The Configuration system can be loaded from the command line argument.

The CreateDefaultBuilder method loads the Command line arguments using config.AddCommandLine(args);

The Command line arguments should follow the specific rules. The Arguments must be passed as Key value pairs. Each Key-value pairs must be separated by space

Each Key-value pairs must be separated by space

Open the startup and goto to configure and add the following code

Open the console window and go to the project directory and invoke the dotnet run with two command line arguments 

The Values Hello and world is displayed on the browser on separate lines

Reading the Environment variables

The config.AddEnvironmentVariables(); loads the Environment values into the configuration collection.

You can then read an environment variable as shown below

Adding our own configuration file

We can also add any number of custom configuration files. This is a nice feature, as we can create separate configuration files for each module/ subsystem. This makes the managing the configuration easier.

Create a test.json in the root folder of the project

Now, open the program.cs and the update the code as shown below.

Now, configuration system automatically adds all the Configuration from the test.json file.

Order Matters

The Order in which configuration files are loaded is matters. If two configuration contains similar keys, the one which loaded last wins.

Summary

We looked at how the new  Configuration system works in ASP.NET Core. The ASP.NET Core Empty project template sets up the application to read the configuration from appsettings.json, appsettings.{env.EnvironmentName}.json, user secrets, environment variables and from command line arguments. We can extend this by adding our own configuration files.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top