Using JSON configuration in ASP.NET

Mauricio SilvaBlog, ConfigLeave a Comment

Photo by Pexels from pixabay.com
In configuration file hell? Take a look at Config, the easiest way to manage your application configuration across all your servers and environments.

The Configuration API provides a way to configure an ASP.NET Core Web application based on a list of name-value pairs. The configuration is read at run time through multiple sources. The name-value pairs can be grouped into a multilevel hierarchy.

There are configuration providers for:

  • File formats (INI, JSON and XML).
  • Command line arguments.
  • Environment variables.
  • .NET objects in memory.
  • Unmanaged Secret Manager storage.
  • An encrypted user repository, such as Azure Key Vault.
  • Custom providers (installed or created).

Each configuration value is mapped to a string key. There is built-in association support for deserializing settings on a custom object (a simple .NET class with properties).

JSON configuration

The following console application uses the JSON configuration provider:

using System;
using System.IO;
// Requires NuGet package
// Microsoft.Extensions.Configuration.Json
using Microsoft.Extensions.Configuration;
public class Program
{
   public static IConfiguration Configuration { get; set; }
   public static void Main(string[] args = null)
   {
       var builder = new ConfigurationBuilder()
           .SetBasePath(Directory.GetCurrentDirectory())
           .AddJsonFile(“appsettings.json”);
       Configuration = builder.Build();
       Console.WriteLine($"option1 = {Configuration["Option1"]}");
       Console.WriteLine($"option2 = {Configuration["option2"]}");
       Console.WriteLine(
           $"suboption1 = {Configuration["subsection:suboption1"]}");
       Console.WriteLine();
       Console.WriteLine("Wizards:");
       Console.Write($"{Configuration["wizards:0:Name"]}, ");
       Console.WriteLine($"age {Configuration["wizards:0:Age"]}");
       Console.Write($"{Configuration["wizards:1:Name"]}, ");
       Console.WriteLine($"age {Configuration["wizards:1:Age"]}");
       Console.WriteLine();
       Console.WriteLine("Press a key…");
       Console.ReadKey();
   }
}

The application reads and displays the following configuration settings:

{
 "option1": "value1_from_json",
 "option2": 2,
 "subsection": {
   "suboption1": "subvalue1_from_json"
 },
 "wizards": [
   {
     "Name": "Gandalf",
     "Age": "1000"
   },
   {
     "Name": "Harry",
     "Age": "17"
   }
 ]
}

The configuration consists of a hierarchical list of name-value pairs in which the nodes are separated by a colon (:).

To retrieve a value, access the Configuration indexer with the corresponding item key:

Console.WriteLine(
    $"suboption1 = {Configuration["subsection:suboption1"]}");

To work with arrays in JSON-formatted configuration sources, use an array index as part of the colon separated by a character. The following example gets the name of the first item in the previous wizards array:

Console.Write($"{Configuration["wizards:0:Name"]}");
// Output: Gandalf

Configuration by environment

It is common to have different configurations for different environments, for example development, testing and production. The CreateDefaultBuilder extension method in an ASP.NET Core 2.x application (or using AddJsonFile and AddEnvironmentVariables directly in an ASP.NET Core 1.x application) adds configuration providers to read JSON files and system configuration sources:

appsettings.json

appsettings. <EnvironmentName> .json

Environment variables

ASP.NET Core 1.x applications need to call AddJsonFile and AddEnvironmentVariables.

See AddJsonFile for an explanation of the parameters. reloadOnChange is only supported in ASP.NET Core 1.1 or later.

The configuration sources are read in the order in which they are specified. In the previous code, the environment variables are read last. The configuration values ​​defined by the environment override those defined in the previous two providers.

Consider the following appsettings.staging.json file:

{
 "Logging": {
   "IncludeScopes": false,
   "LogLevel": {
     "System": "Information",
     "Microsoft": "Information"
   }
 },

 "MyConfig": "My Config Value for staging."
}

In the following code, Configure reads the value of MyConfig:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   var myConfig = Configuration["MyConfig"];
   // use myConfig
   if (env.IsDevelopment())
   {
       app.UseDeveloperExceptionPage();
       app.UseBrowserLink();
   }
   if (env.IsProduction() || env.IsStaging())
   {
       app.UseExceptionHandler("/Error");
   }
   app.UseStaticFiles();
   app.UseMvcWithDefaultRoute();
}

The environment is typically defined as Development, Staging, or Production.

Configuration Considerations:

  • IOptionsSnapshot can reload configuration data when it changes.
  • Configuration keys are not case-sensitive.
  • Never store passwords or other sensitive data in the configuration provider code or in the plain text configuration files. Do not use production secrets in test or development environments. Specify secrets outside the project so that they are not accidentally compromised with a source repository. Learn more about using multiple environments and managing secure storage of application secrets in development.
  • To know hierarchical configuration values ​​specified in environment variables, colon (:) may not work on all platforms. Double underscore (__) is compatible with all platforms.
  • When interacting with the API configuration, a colon (:) works on all platforms.

Leave a Reply

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

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