- catalog
. net configuration configuration
Dotnet configuration source code:https://github.com/dotnet/runtime/tree/master/src/librariesIn which Microsoft.Extensions.Configuration Opening item
Official configuration document:
- https://docs.microsoft.com/en-us/dotnet/core/extensions/configuration
- https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1
. 5 net environment:
Nuget package:Microsoft.Extensions.Configuration
Memory configuration
IConfigurationRoot configuration = new ConfigurationBuilder()
//Add memory configuration
.AddInMemoryCollection(new Dictionary
{
["KeyName1"] = "KeyValue1"
})
.Build();
///Get configuration
Console.WriteLine(configuration["KeyName1"]); // KeyValue1
File configuration
Nuget package:
- Json:
Microsoft.Extensions.Configuration.Json
- Ini:
Microsoft.Extensions.Configuration.Ini
- Xml:
Microsoft.Extensions.Configuration.Xml
Suppose there are three documents in the project as follows:
a. JSON file
{
"Key": "KeyValue",
"Person": {
"Name": "MyName",
"Age": 10
}
}
a. XML file
KeyValue
MyName
10
a. INI file
Key = KeyValue
[Person]
Name = My Name
Age = 10
//JSON file configuration
IConfiguration jsonConfiguration = new ConfigurationBuilder()
. addjsonfile ("a.json") // add JSON file configuration
.Build();
Console.WriteLine(jsonConfiguration["Key"]); // KeyValue
//Use ':' to separate 'parent section' and 'child section'
Console.WriteLine(jsonConfiguration["Person:Name"]); // MyName
Console.WriteLine(jsonConfiguration["Person:Age"]); // 10
//XML file configuration
IConfiguration xmlConfiguration = new ConfigurationBuilder()
. addxmlfile ("a.xml") // add XML file configuration
.Build();
Console.WriteLine(xmlConfiguration["Key"]); // KeyValue
Console.WriteLine(xmlConfiguration["Person:Name"]); // MyName
Console.WriteLine(xmlConfiguration["Person:Age"]); // 10
//INI file configuration
IConfiguration iniConfiguration = new ConfigurationBuilder()
. addinifile ("a.ini") // add INI file configuration
.Build();
Console.WriteLine(iniConfiguration["Key"]); // KeyValue
Console.WriteLine(iniConfiguration["Person:Name"]); // MyName
Console.WriteLine(iniConfiguration["Person:Age"]); // 10
Optional file configuration
The default configuration file is not optional. The file must exist, otherwise an exception will be thrown. Set the second parameter to make the configuration file optional
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("a. optional.json ", true / * optional profile * /)
.Build();
Reload configuration when file content changes
By default, the configuration will not be reloaded when the file content changes. By setting the third parameter, the configuration will be reloaded when the file content changes
IConfiguration configuration = new ConfigurationBuilder()
.AddJsonFile("a.json", false, true)
.Build();
do
{
Console.WriteLine(configuration["Key"]);
var consoleKeyInfo = Console.ReadKey();
if (consoleKeyInfo.Key == ConsoleKey.Q)
{
Console.WriteLine("Quit");
break;
}
} while (true);
Hierarchical configuration
The configuration is divided into “layers”. The parent section and the child section are separated by “:”
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["KeyName1:SubKey:SubKey2"] = "SubKeyValue",
["KeyName1:SubKey"] = "SubKeyValue2",
["keyname1: subkey"] = "overridesubkeyvalue" // override
})
.Build();
Console.WriteLine(configuration["KeyNaKeyName1:SubKey:SubKey2me1"]); // SubKeyValue
Console.WriteLine(configuration["KeyNaKeyName1:SubKey"]); // OverrideSubKeyValue
When there is the same key, the later value will override the previous value. For example, the key in the upper instance is keyname1: the value of subkey is overridden
IConfigurationSection
The iconfigurationsection interface inherits the child iconfiguration and adds the following attributes
- Key: key name
- Path: complete path
- Value: value
Iconfiguration:: getsection get section
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["KeyName1"] = "KeyValue1",
["KeyName1:SubKey1"] = "SubKeyValue1",
["KeyName1:SubKey2"] = "SubKeyValue2",
["KeyName1:SubKey3:A"] = "A",
}).Build();
//Gets the specified subsection
IConfiguration section = configuration.GetSection("KeyName1");
Console.WriteLine(JsonSerializer.Serialize(section));
// {"Key":"KeyName1","Path":"KeyName1","Value":"KeyValue1"}
//Get sub section in
Console.WriteLine(section["SubKey1"]); // SubKeyValue1
One moreGetRequiredSection
Methods, andGetSection
The only difference is that an exception is thrown when the configuration section to get does not exist
Iconfigurationsection:: exist determines whether a section exists
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["KeyName1"] = "KeyValue1
}).Build();
Console.WriteLine(configuration.GetSection("ABC").Exist()); // False
Console.WriteLine(configuration.GetSection("KeyName1").Exist()); // True
Iconfiguration:: getchildren get all child sections
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["KeyName1"] = "KeyValue1",
["KeyName1:SubKey1"] = "SubKeyValue1",
["KeyName1:SubKey2"] = "SubKeyValue2",
["KeyName1:SubKey3:A"] = "A",
}).Build();
//Get all sub sections
IEnumerable sections = configuration.GetSection("KeyName1").GetChildren();
Console.WriteLine(JsonSerializer.Serialize(sections));
/*
[
{"Key":"SubKey1","Path":"KeyName1:SubKey1","Value":"SubKeyValue1"},
{"Key":"SubKey2","Path":"KeyName1:SubKey2","Value":"SubKeyValue2"},
{"Key":"SubKey3","Path":"KeyName1:SubKey3","Value":null}
]
*/
//Get all sub sections
var sections2 = configuration.GetSection("KeyName1:SubKey3").GetChildren();
Console.WriteLine(JsonSerializer.Serialize(sections2));
/*
[
{"Key":"A","Path":"KeyName1:SubKey3:A","Value":"A"}
]
*/
Configuration chain
Add existing configurations to the configuration and link them together
IConfiguration configuration1 = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["A"] = "A Value"
})
.Build();
IConfiguration configuration2 = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["B"] = "B Value"
})
.Build();
IConfiguration configuration = new ConfigurationBuilder()
.AddConfiguration(configuration1)
.AddConfiguration(configuration2)
.Build();
Console.WriteLine($"A:{configuration["A"]}");
Console.WriteLine($"B:{configuration["B"]}");
Connection string
In Asp.Net The configuration of connection string is almost essential. An extension method of configuration is specially defined to obtain the connection string
Connect string toConnectionStrings
Father’s Day
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["ConnectionStrings:Default"] = "Default ConnectingString",
["ConnectionStrings:SqlServer"] = "SqlServer ConnectingString",
["ConnectionStrings:PostgreSql"] = "PostgreSql ConnectingString",
})
.Build();
Console.WriteLine($"Default ConnectionString:{configuration.GetConnectionString("Default")}");
Console.WriteLine($"Default SqlServer:{configuration.GetConnectionString("SqlServer")}");
Console.WriteLine($"Default PostgreSql:{configuration.GetConnectionString("PostgreSql")}");
Configure binding
Nuget package: Microsoft.Extensions.Configuration .Binder
Binding a configuration to an object instance is similar to deserializing the configuration to an object
class ConfigurationModel2
{
public string A { get; set; }
public string B { get; set; }
private string C { get; set; }
public string GetC()
{
return C;
}
}
IConfiguration configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["MyBind:A"] = "A Value",
["MyBind:B"] = "B Value",
["MyBind:C"] = "C Value",
})
.Build();
var myBind = new ConfigurationModel2
{
A = "A Ini Value",
B = "B Ini Value",
};
configuration.GetSection("MyBind").Bind(myBind);
Console.WriteLine(myBind.A); // A Value
Console.WriteLine(myBind.B); // B Value
Console.WriteLine ( myBind.GetC ()); // null, it will not be bound to non public properties by default
Specify key when Binding
var myBind2 = new ConfigurationModel2();
configuration.Bind("MyBind", myBind2);
Console.WriteLine(myBind2.A); // A Value
Console.WriteLine(myBind2.B); // B Value
Console.WriteLine(myBind2.GetC()); // Null
Binding non public properties
var myBind3 = new ConfigurationModel2();
configuration.GetSection ("MyBind").Bind(myBind3, bindOption => { bindOption.BindNonPublicProperties =True; // sets the binding non public attribute});
Console.WriteLine(myBind3.A); // A Value
Console.WriteLine(myBind3.B); // B Value
Console.WriteLine(myBind3.GetC()); // C Value
GetValue, gets the value of the specified key and converts it to the specified type
Supported types include: int, uint, short, USHORT, long, ulong, bool, byte, sbyte, char, decimal, double, float, datetime, DateTimeOffset, timespan, URI, and guid
Instance (instance type and data from official test code)
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["int"] = "2147483647",
["uint"] = "4294967295",
["short"] = "32767",
["ushort"] = "65535",
["long"] = "-9223372036854775808",
["ulong"] = "18446744073709551615",
["bool"] = "trUE",
["byte"] = "255",
["sbyte"] = "127",
["char"] = "\uffff",
["decimal"] = "79228162514264337593543950335",
["double"] = "1.79769e+308",
["float"] = "3.40282347E+38",
["DateTime"] = "2015-12-24T07:34:42-5:00",
["DateTimeOffset"] = "12/24/2015 13:44:55 +4",
["TimeSpan"] = "99.22:22:22.1234567",
["Uri"] = "http://www.bing.com",
["Guid"] = "CA761232-ED42-11CE-BACD-00AA0057B223",
}).Build();
Console.WriteLine(configuration.GetValue("int")); // 2147483647
Console.WriteLine(configuration.GetValue("uint")); // 4294967295
Console.WriteLine(configuration.GetValue("short")); // 32767
Console.WriteLine(configuration.GetValue("ushort")); // 65535
Console.WriteLine(configuration.GetValue("long")); // -9223372036854775808
Console.WriteLine(configuration.GetValue("ulong")); // 18446744073709551615
Console.WriteLine(configuration.GetValue("bool")); // True
Console.WriteLine(configuration.GetValue("byte")); // 255
Console.WriteLine(configuration.GetValue("sbyte")); // 127
Console.WriteLine(configuration.GetValue("char")); // �
Console.WriteLine(configuration.GetValue("decimal")); // 79228162514264337593543950335
Console.WriteLine(configuration.GetValue("double")); // 1.79769E+308
Console.WriteLine(configuration.GetValue("float")); // 3.4028235E+38
Console.WriteLine(configuration.GetValue("DateTime")); // 12/24/2015 8:34:42 PM
Console.WriteLine(configuration.GetValue("DateTimeOffset")); // 12/24/2015 1:44:55 PM +04:00
Console.WriteLine(configuration.GetValue("TimeSpan")); // 99.22:22:22.1234567
Console.WriteLine(configuration.GetValue("Uri")); // http://www.bing.com/
Console.WriteLine(configuration.GetValue("Guid")); // ca761232-ed42-11ce-bacd-00aa0057b223
GetValue provides a default value
Console.WriteLine ( configuration.GetValue ("INT2", - 1 / * default * /));
Get(), binding configuration to the specified type
supportGetValue
Supports all types, supports binding arrays
class ConfigurationModel
{
public int Int { get; set; }
public float Float { get; set; }
public Uri Uri { get; set; }
public Guid Guid { get; set; }
public string[] Strings { get; set; }
}
class Program
{
static void Main(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary
{
["int"] = "2147483647",
["float"] = "3.40282347E+38",
["Uri"] = "http://www.bing.com",
["Guid"] = "CA761232-ED42-11CE-BACD-00AA0057B223",
["Strings:0"] = "Value 0",
["Strings:1"] = "Value 1",
["Strings:2"] = "Value 2"
}).Build();
ConfigurationModel model = configuration.Get();
Console.WriteLine(JsonSerializer.Serialize(model));
/*
{
"Int": 2147483647,
"Float": 3.4028235E+38,
"Uri": "http://www.bing.com",
"Guid": "ca761232-ed42-11ce-bacd-00aa0057b223"
"Strings": [
"Value 0",
"Value 1",
"Value 2"
]
}
*/
}
}
Command line configuration
Set the command line parameter arrayargs
Add to configuration
Nuget package: Microsoft.Extensions.Configuration .CommandLine
The following forms of command line configuration are supported:
- Parameters and values pass through
=
division - Parameter usage
/
Prefixes, parameters and values are passed through=
Or space segmentation - Parameter usage
--
Prefixes, parameters and values are passed through=
Or space segmentation
Values can be quoted in double or single quotation marks. For example, when a value contains special characters (such as spaces), double or single quotation marks must be used
example:
class Program
{
static void Main(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
. addcommandline (args) // add configuration from command line
.Build();
Console.WriteLine($"args:{String.Join(',', args)}");
Console.WriteLine(configuration["a"]);
Console.WriteLine(configuration["b"]);
Console.WriteLine(configuration["c"]);
Console.WriteLine(configuration["d"]);
Console.WriteLine(configuration["e"]);
Console.WriteLine(configuration["f"]);
Console.WriteLine(configuration["g"]);
}
}
Operation procedure:
dotnet run -- a=av b="b v" /c cv /d=dv --e=ev --f fv -g gv
The output is as follows
args:a=av,b=b v,/c,cv,/d=dv,--e=ev,--f,fv,-g,gv
av
b v
cv
dv
ev
fv
Exchange mapping to realize alias and short name of command line configuration
Suppose you have the following command line configuration
- Name: name
- n: The short name of name
- File: file
- OutputFile: alias of file
- f: The short name of the file
The dictionary key for an exchange map must start with ‘-‘ or ‘-‘
- -: represents a short name
- –: indicates an alias
example:
class Program
{
static void Main(string[] args)
{
IDictionary switchMappings = new Dictionary
{
["-n"] = "name",
["-f"] = "file",
["--outputFile"] = "file",
};
IConfigurationRoot configuration = new ConfigurationBuilder()
.AddCommandLine(args, switchMappings)
.Build();
Console.WriteLine($"args:{String.Join(',', args)}");
Console.WriteLine($"name:{configuration["name"]}");
Console.WriteLine($"file:{configuration["file"]}");
}
}
UserSecret
Add user key, etc. to configuration
Nuget package: Microsoft.Extensions.Configuration .UserSecrets
Introduction to usersecret
Save the password and other configuration in the computer’ssecrets.json
In the document, not in the project file
secrets.json
file location
- Windows:
%APPDATA%\Microsoft\UserSecrets\\secrets.json
- Linux、macOS:
~/.microsoft/usersecrets//secrets.json
In this way, you can have different configuration information on different computers
Use usersecret to configure
Before using the usersecret configuration, you need to specify the usersecretid, which is in the form of a guid
secrets.json
The folder name of the file isUserSecretId
Specify usersecretid in the project configuration
Run command:dotnet user-secrets init
After running, it will be automatically in the project configuration file.csproj
Generated inUserSecretsId
Then pass in the assembly of the project in the parameter
IConfiguration configuration = new ConfigurationBuilder()
.AddUserSecrets( Assembly.GetExecutingAssembly ()) // add user key days to configuration
.Build();
Console.WriteLine($"test-key:{configuration["my-key"]}");
Specify the usersecretid directly in the parameter
IConfiguration configuration = new ConfigurationBuilder()
.AddUserSecrets("8B348FF5-ED73-41B7-8769-1CEF70421DEC")
.Build();
Console.WriteLine($"test-key:{configuration["my-key"]}");
AddUserSecrets
AndAddJson
It also loads the file configuration, so there areOptional configuration parametersandReload configuration fileParameters of
Use of usersecret tool
The user secrets tool has the following commands
- Init: initialization, set a usersecretid for the project to enable key configuration
- Clear: clear the project key configuration
- Set: set the key configuration
dotnet user-secrets set my-key value
- Remove: remove key configuration
dotnet user-secrets remove my-key
- List: View key configuration
Environment variable configuration
Add environment variable information to configuration
Nuget package: Microsoft.Extensions.Configuration .EnvironmentVariables
example:
IConfiguration configuration = new ConfigurationBuilder()
. addenvironmentvariables() // add environment variable information to configuration
.Build();
Console.WriteLine($"path:{configuration["PATH"]}");
Environment variable prefix
You can specify an environment variable prefix, and only the environment variables with this prefix will be loaded
example:
Suppose you have the following environment variables
- MyPrefix_A:A Value
- MyPrefix_B:B Value
- MyPrefix2_A2:A Value 2
- MyPrefix2_B2:B Value 2
IConfiguration configuration = new ConfigurationBuilder()
.AddEnvironmentVariables("MyPrefix_")
.AddEnvironmentVariables("MyPrefix2_")
.Build();
Console.WriteLine($"path:{configuration["A"]}"); // A Value
Console.WriteLine($"path:{configuration["B"]}"); // B Value
Console.WriteLine($"path:{configuration["A2"]}"); // A Value 2
Console.WriteLine($"path:{configuration["A2"]}"); // B Value 2