SoFunction
Updated on 2025-03-04

Core configuration settings

AConfigurationPackage, used to apply key-value pairs established based on configuration providers. Here I will briefly introduce its usage in the form of json file configuration.

First define a configuration file:

{
    "key1": "value1",
    "key2": -1,
        "subsection":  {
            "key1": "value2",
            "key2": -5
    }
}

The following are the basic usages:

var configBuilder = new ConfigurationBuilder().AddJsonFile("");
var config        = ();

var value1 = <string>("key1");
var value2 = <int>("key2");

.net core distributes configuration operations in two objects: ConfigurationBuilder and IConfigurationRoot. ConfigurationBuilder is used to configure data sources, and IConfigurationRoot provides unified read operations.

Data source:

The configuration provider reads configuration data from various configuration sources to key-value pairs. It supports many configuration methods, and the common ones are:

  • Command line parameters

  • Environment variables

  • .NET objects in memory

  • Set files (Ini, xm, Json)

  • Custom provider

Basically, commonly used configuration data sources are supported, supporting multi-data source configuration and custom data sources, which are very flexible and convenient. For specific configuration methods, please refer to the official documentation.Configuration in Core

CreateDefaultBuilder

To simplify configuration, a function CreateDefaultBuilder is provided in the core that implicitly provides calls to ConfigurationBuilder, and the configuration loading of the following configuration files is provided in sequence:

  • appsettings.{Environment}.json。

  • A secret manager that applies to runtime in a Development environment using the entry assembly.

  • Environment variables.

  • Command line parameters

For more details, please refer to the official documentation:Set up the host

Read configuration

The basic reading method is demonstrated in the previous example:

var value1 = <string>("key1");
var value2 = <int>("key2");

In addition to this method, you can also read it in the form of an object through the Bind method:

class ConfigData
{
    public string Key1 { get; set; }
     public int Key2 { get; set; }
}

var cfgData = new ConfigData();
(cfgData);

In addition, for the configuration of child nodes, you can also locate the child nodes through the GetSection function and then read them in the previous way, for example:

var value1 = ("subsection").GetValue<string>("key1");
var cfgData = ("subsection").Get<ConfigData>();

Reference article

Configuration in Core

This is all about this article about the Configuration package of Core configuration settings. I hope it will be helpful to everyone's learning and I hope everyone will support me more.