ASP.NET Core AppSettings.json file

ASP.NET Core AppSettings.json File

In this article, I will discuss the use and importance of the ASP.NET Core AppSettings.json File with Examples. Please read our previous article discussing the ASP.NET Core Startup Class with Examples. As part of this article, we will 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 do you access the configuration information in the ASP.NET Core Application?
  4. What is the Configuration Execution Order in ASP.NET Core Application?
  5. What are the Default Orders for Reading the Configuration Sources?
  6. Real-time Examples of ASP.NET Core AppSettings.json file.
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 know the importance of the web.config file. In our traditional ASP.NET application, we generally 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 configuration sources, such as

  1. Files (appsettings.json, appsettings.{Environment}.json, where the {Environment} is nothing but the application’s current hosting environments such as Development, Staging, or Production)
  2. User Secrets
  3. Environment Variables
What is the ASP.NET Core AppSettings.json File?

The appsettings.json file in an ASP.NET Core application is a JSON formatted file that stores configuration data. In this file, you can keep settings like connection strings, application settings, logging configuration, and anything else you want to change without recompiling your application. The settings in this file can be read at runtime and overridden by environment-specific files like appsettings.Development.json or appsettings.Production.json.

When we create an ASP.NET Core Web Application with an Empty or Razor Pages or MVC or Web API Project Template, Visual Studio automatically creates the appsettings.json file for us, as shown in the image below.

What is ASP.NET Core AppSettings.json File

If you open the ASP.NET Core appsettings.json file, you see the following code created by Visual Studio by default.

ASP.NET Core AppSettings.json File

Note: The appsettings.json file typically resides in the root directory of your ASP.NET Core project. You can add multiple appsettings.json files with different names, such as appsettings.development.json, appsettings.production.json, etc., to manage configuration for different environments (e.g., development, production, staging).

Now, I will add a key named MyCustomKey within this file. To do so, please modify the appsettings.json file as shown below. You must store the value as a key-value pair as a JSON file.

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

Here’s what each section typically means:

  • Logging: Defines the logging level for different components of the application.
  • AllowedHosts: Specifies the hosts that the application will listen to.
  • MyCustomSettings: A custom section that you define for your own application settings.

Configuration Sections: The file is typically divided into sections that represent different aspects of the application settings. For example, you might have sections like ConnectionStrings, Logging, or custom sections for your application-specific settings.

How Do We Access the Configuration Information in the ASP.NET Core Application?

To access the configuration information from the appsettings.json file within the Main method of the Program class or any other class, we need to use the IConfiguration service, which ASP.NET Core Framework provides. So, what we need to do is first we need to call the Configuration property using the builder object, which is going to return the ConfigurationManager instance as follows:

ConfigurationManager configuration = builder.Configuration;
Once we get the ConfigurationManager instance, we can access the Configuration Information from the appsettings.json file in two ways. They are as follows:

Method 1: Using the GetValue Generic Method of the ConfigurationManager Class
In this case, we need to specify the type as a string, as we will return the string value from the appsettings.json file. For the GetValue method, we must specify the string key name as MyCustomKey.
string MyCustomKeyValue = configuration.GetValue<string>(“MyCustomKey”);

Method 2: Using the ConfigurationManager Class Indexer
In this case, we need to specify the string key name as the indexer as follows.
string MyCustomKeyValue = configuration[“MyCustomKey”];

So, let us modify the Main method of the Program class as follows to access the Configuration Information from the appsettings.json file.

using System.Text.RegularExpressions;

namespace FirstCoreWebApplication
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            var app = builder.Build();

            // Get the Configuration Service.
            ConfigurationManager configuration = builder.Configuration;

            //Get the Value
            string MyCustomKeyValue = configuration.GetValue<string>("MyCustomKey");
            //string MyCustomKeyValue = configuration["MyCustomKey"];

            app.MapGet("/", () => $"{MyCustomKeyValue}");

            app.Run();
        }
    }
}

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

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <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

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

Before understanding the execution order, let’s look at the appsettings.Development.json file. As shown in the image below, you can find this file within your project’s appsettings.json file.

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

Environment-Specific Files: ASP.NET Core supports environment-specific configuration files. This means you can have different versions of appsettings.json for different environments, like appsettings.Development.json, appsettings.Staging.json, and appsettings.Production.json. The appropriate file is loaded based on the current environment, allowing for different configurations in each environment.

Modify the appsettings.Development.json File.

Let us add the same MyCustomKey to this appsettings.Development.json file, which we added to the appsettings.json file. So, modify the appsettings.Development.json file as shown below. 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },

  "MyCustomKey": "MyCustomKey Value coming from appsettings.Development.json"
}

As you can see, we use the same key in the appsettings.json file with a different value. Now run the application and see the output as shown below.

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

As you can see from the above output, it fetches the MyCustomKey Value from the appsettings.Development.json file. I need to clarify that if you have a configuration setting in multiple configuration sources with the same configuration key, the later configuration sources will override the earlier configuration sources. 

What are the Default Orders for Reading the Configuration Sources in ASP.NET Core or .NET 6?

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

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 for Reading the Configuration Sources in ASP.NET Core or in .NET 6

With this change now, run the application and display the value from the environment variable.

What are the Default Orders for Reading the Configuration Sources in ASP.NET Core or in .NET 6

You can also change this default order or add your own custom configuration sources to the existing ones. In our upcoming articles, we will discuss setting up a custom configuration source.

ASP.NET Core AppSettings.json File Real-Time Examples

Here are some real-time examples of how appsettings.json can be used in ASP.NET Core applications:

Database Connection Strings:

In this example, a connection string is defined for a database. The application can access this connection string to interact with the database.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  }
}
Logging Configuration

In this example, the logging levels are configured for the application and specific namespaces.

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
External Service Configuration

This example shows how to store API settings for external services, like base URLs and API keys.

{
  "ExternalService": {
    "BaseUrl": "https://api.example.com/",
    "ApiKey": "Your-Api-Key-Here"
  }
}
Custom Application Settings

Custom settings specific to the application, like page size for pagination or support email addresses.

{
  "ApplicationSettings": {
    "PageSize": 20,
    "SupportEmail": "support@example.com"
  }
}
Authentication Settings

Settings related to authentication, like JWT settings in this case.

{
  "Authentication": {
    "Jwt": {
      "Key": "Your-Secret-Key",
      "Issuer": "YourIssuer",
      "Audience": "YourAudience"
    }
  }
}
API Rate Limiting

Configurations for API rate limiting.

{
  "RateLimiting": {
    "EnableRateLimit": true,
    "MaxRequestsPerSecond": 5
  }
}

Overall, appsettings.json is a flexible and convenient way to manage configuration settings in ASP.NET Core applications. It makes it easy to separate configuration from code and adapt your application to different environments.

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

5 thoughts on “ASP.NET Core AppSettings.json file”

    1. blank

      In the controller, you will have to create a constructor that takes IConfiguration interface just as u see above in startup constructor. eg Just imagine you have DefaultController and u need to access config value. You decare a constructor as below

      //constructor
      public Default()
      {
      }

      here we will have to pass IConfiguration object to constructor (Constructor dependency injection)

      public Default(IConfiguration config)
      {
      }

      Now we need to declare a private field that holds this value
      private IConfiguration _config;

      Now we will assign to _config and everything loos like below
      //field
      private IConfiguration _config;
      //Dependency Injection to inject the Configuration object
      public Default(IConfiguration config)
      {
      _config = config;
      }

      Now you can access key value like below

      var config value = _config[“keyname”];

Leave a Reply

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