ASP.NET Core appsettings.json file

ASP.NET Core appsettings.json file in Detail

In this article, I am going to discuss the use and importance of ASP.NET Core appsettings.json file in detail. Please read our previous article before proceeding to this article where we discussed the use and importance of ASP.NET Core launchSettings.json file. As part of this article, we are going to discuss the following pointers in detail.

  1. What are the different Configuration Sources available in ASP.NET Core application?
  2. What is ASP.NET Core appsettings.json file?
  3. How to access the configuration information in ASP.NET Core Application?
  4. What is Configuration Execution Order in ASP.NET Core Application?
  5. What is the Default Orders of reading the configuration sources?
  6. How to Pass Config value from Command Line in ASP.NET Core Application?
What are the different Configuration Sources available in ASP.NET Core application?

If you have worked with the previous versions of ASP.NET application, then you make know the importance of the web.config file. In previous versions of ASP.NET application, we generally used to store the application configuration settings such as database connection strings, any application scope global variables and many more within the web.config file.

But in ASP.NET Core, the application configuration settings can come from different configurations sources such as

  1. Files (appsettings.json, appsettings.{Environment}.json, where the {Environment} is the nothing but the applications current hosting environments such as Development, Staging or Production)
  2. User secrets
  3. Environment variables
  4. Command-line arguments
What is ASP.NET Core appsettings.json File?

When we create an asp.net core web application with an Empty project template, then visual studio automatically creates the appsettings.json file for us as shown in the below image.

ASP.NET Core appsettings.json file

If you open the appsettings.json file, then you see the following code.

ASP.NET Core appsettings.json file

Now I am going to add a key with the name MyCustomKey within this file. To do so, please modify the appsettings.json file as shown below.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "MyCustomKey": "MyCustomKey Value coming from appsettings.json"
}

As it is a JSON file, you need to store the value in the form of key-value pair.

How to access the configuration information in ASP.NET Core application?

To access the configuration information within the Startup class, you need to use the IConfiguration service which is provided by the ASP.NET Core Framework. So what you need to do is just inject the IConfiguration service through the constructor of the Startup class. To do so modify the Startup class which is present in the Startup.cs file as shown below. 

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace FirstCoreWebApplication
{
    public class Startup
    {
        private IConfiguration _config;

        // Here we are using Dependency Injection to inject the Configuration object
        public Startup(IConfiguration config)
        {
            _config = config;
        }
        
        public void ConfigureServices(IServiceCollection services)
        {
        }
        
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync(_config["MyCustomKey"]);
            });
        }
    }
}
Explanation of the above code:

First, we created a private variable of type IConfiguration. Then through constructor dependency injection we inject the IConfiguration object and store it within the private variable. The following code exactly does this.

Creating Configuration object

Then we access the configuration variable i.e. MyCustomKey using the IConfiguration service instance. The following piece of code exactly does the same thing.

Accesing the configuration value in asp.net core application

Set the AspNetCoreHostingModel value to InProcess in the application’s project file as shown below.

<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

Now run the application and you see the value as expected in the browser window as shown in the below image.

Config Key Output

Dependency Injection Design Pattern

In our previous versions of ASP.NET applications, the Dependency Injection design pattern was optional. But if you want to configure it in your application, then you need to use some of the frameworks like Ninject, StructureMap, IUnity container, etc.

But in ASP.NET Core application Dependency Injection is an integral part and the framework provides the inbuilt support for dependency injection. The Dependency Injection Design Pattern allows us to develop loosely coupled systems which are extensible and also easy to testable. If this is not clear at the moment don’t worry, we will discuss the Dependency Injection design pattern in great details in our upcoming articles with asp.net core application. If you want to know how the dependency injection design pattern is used with the previous versions of ASP.NET application, then read the following article.

https://dotnettutorials.net/lesson/dependency-injection-design-pattern-csharp/

What is Configuration Execution Order in ASP.NET Core Application?

Before understanding the execution order, let’s have a look at the appsettings.Development.json file. You can find this file within the appsettings.json file as shown below.

appsettings.Development.json file

Let us modify the appsettings.Development.json as shown below.

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "MyCustomKey": "MyCustomKey Value coming from appsettings.Development.json"
}

As you can see we are using the same key as we use in the appsettings.json file. Now run the application and see the output as shown below.

appsetting.development.output

As you see from the above output, it fetches the MyCustomValue from the appsettings.Development.json file.

The point that I need to make you clear, if you have a configuration setting in multiple configuration sources with the same configuration key, then the later configuration sources will override the earlier configuration sources. 

What is the Default Orders of reading the configuration sources?

The default orders in which the various configuration sources are read for the same key are as follows

  1. appsettings.json, 
  2. appsettings.{Environment}.json here we use appsettings.development.json
  3. User secrets
  4. Environment variables
  5. Command-line arguments

Now we already have MyCustomKey in two places i.e. appsettings.json and appsettings.development.json. Now add the same key as “MyCustomKey”: “MyCustomKey Value coming from Environment Variable of launchsSettings.json” in the IIS Express profile section of the launchSettings.json file as shown below.

Adding Environment Variable

With this change now run the application and it should display the value coming from the environment variable.

Value coming From the Environment Variable

How to Pass Config value from Command Line in ASP.NET Core Application?

Command Line Argument Values

Now open the browser window and type the following URL

Value coming From CLI

The following is the auto-generated program class.

Program Class Main Method

As you can see the Main() method of the Program class calls the CreateWebHostBuilder() method. Then the CreateWebHostBuilder() method calls the CreateDefaultBuilder() method of the WebHost class. This CreateDefaultBuilder() method is the method which sets the default order in which all the configuration sources are read. As asp.net core is open source so you can find the code of this WebHost class in the following GitHub link.

https://github.com/aspnet/MetaPackages/blob/release/2.2/src/Microsoft.AspNetCore/WebHost.cs

If you want then you can also change this default order or even if you want then you can add your own custom configuration sources along with the existing configuration sources. In our upcoming articles, we will discuss setting up a custom configuration source.

In the next article, we are going to discuss one more important concept i.e. Middleware in ASP.NET Core application. Here, in this article, I try to explain the ASP.NET Core appsettings.json file in detail. I hope this article will help you to understand the need and use of ASP.NET Core appsettings.json file.

Leave a Reply

Your email address will not be published. Required fields are marked *