Excerpt from here
Take JSON as an example
Json configuration, the Microsoft.Extensions.Configuration.Json package needs to be installed.
Call Addjsonfile to add the JSON-configured provider to Configurationbuilder.
classprogram{ Public StaticIconfigurationroot Configuration {Get;Set; } Static voidMain (string[] args) { varBuilder =NewConfigurationbuilder (). Setbasepath (Directory.GetCurrentDirectory ()). Addjsonfile ("Appsettings.json"); Configuration=Builder. Build (); }}
Setbasepath is the specified directory from which to start looking for Appsettings.json. If Appsettings.json is in the Configs directory, then the call addjsonfile should specify a path of "Configs/appsettings.json".
Here is the JSON configuration for the demo, followed by all the ways to read it
{ "AppId":"12345", "Logging": { "Includescopes":false, "LogLevel": { "Default":"Debug", "System":"Information", "Microsoft":"Information" } }, "Granttypes": [ { "Name":"Authorization_code" }, { "Name":"Password" }, { "Name":"client_credentials" } ]}
Read JSON configuration
1. Read with key
configuration[ " AppId "]; // result 12345 Configuration[ " logging:includescopes " Span style= "COLOR: #800000" ""; // Configuration[ " logging:loglevel:default "]; // result Debug Configuration[ " granttypes:0:name "]; // result authorization_code
Read the nested configuration, separated by a colon, read the array form of the configuration, use the array's subscript index, 0 represents the first.
If the configuration is used elsewhere, the iconfiguration can be injected through a constructor function.
First, configure IConfiguration dependencies
Services. Addsingleton<iconfiguration> (Configuration);
And then inject it through the constructor
Private ReadOnly iconfiguration _configuration; Public GetConfig (iconfiguration configuration) { = configuration;}
2. Using getvalue<t>
This is an extension method that uses it to install the Microsoft.Extensions.Configuration.Binder package.
configuration.getvalue<int> ("AppId",12345);//result 12345configuration.getvalue<BOOL> ("Logging:includescopes",false);//false Resultconfiguration.getvalue<string> ("Logging:LogLevel:Default","Debug");//result Debugconfiguration.getvalue<string> ("Granttypes:0:name","Authorize_code");//result Authorization_code
The generic form of the GetValue method has two overloads, one is GetValue ("key") and the other can specify the default value, GetValue ("key", DefaultValue). If the configuration of key is not present, the first result is default (T), and the second result is the specified value.
configuration files for. NET Core