ASP.NET Core appsettings.json file

ASP.NET Core appsettings.json file

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

  1. What are the different Configuration Sources available in the ASP.NET Core application?
  2. What is the ASP.NET Core appsettings.json file?
  3. How to access the configuration information in ASP.NET Core Application?
  4. What is the 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 the ASP.NET Core application?

If you have worked with the previous versions of the 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 or Razor Pages or MVC Template or Web API Template, then the visual studio automatically creates the appsettings.json file for us as shown in the below image.

What is ASP.NET Core appsettings.json File?

The appsettings.json file is an application configuration file used to store configuration settings such as database connections strings, any application scope global variables, etc. If you open the ASP.NET Core appsettings.json file, then you see the following code by default which is created by visual studio.

What are the different Configuration Sources available in the ASP.NET Core application?

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. As it is a JSON file, you need to store the value in the form of key-value pair.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "MyCustomKey": "MyCustomKey Value coming from appsettings.json"
}
How to access the configuration information in the 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;
using Microsoft.Extensions.Hosting;

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, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

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

First, we created a private variable of type IConfiguration _config (This IConfiguration interface belongs to Microsoft.Extensions.Configuration namespace, so bring this namespace first). Then through constructor dependency injection we inject the IConfiguration object and store it within the private variable _config. The following code exactly does this.

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

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

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

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

<Project Sdk="Microsoft.NET.Sdk.Web">
 <PropertyGroup>
  <TargetFramework>netcoreapp3.1</TargetFramework>
  <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
 </PropertyGroup>
</Project>

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

ASP.NET Core appsettings.json file

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 a traditional .NET 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 that 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 detail 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 the 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 project as shown in the below image.

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

Let us modify the appsettings.Development.json as shown below.
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "MyCustomKey": "MyCustomKey Value coming from appsettings.Development.json"
}

As you can see, here 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.

appsettings.json file in ASP.NET Core Application

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 are 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

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.

What are the Default Orders of reading the configuration sources?

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

appsettings.json file in .NET Core Application

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

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

Now open the browser window and type the following URL

appsettings.json file in ASP.NET Core Application

The following is the auto-generated program class.

appsettings.json file in .NET Core

As you can see the Main() method of the Program class calls the CreateHostBuilder() method. Then the CreateHostBuilder() method calls the CreateDefaultBuilder() method on the Host class. This CreateDefaultBuilder() method is the method that sets the default order in which all the configuration sources are read.

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 the ASP.NET Core appsettings.json file.

2 thoughts on “ASP.NET Core appsettings.json file”

Leave a Reply

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