. NET core usage configuration files
In. NET core, the read of the configuration file is provided through IConfiguration, and the assembly is Microsoft.Extensions.Configuration
, corresponding to a series of implementations, through which the configuration files of the type Json/xml/ini can be read.
In this section of the example, we use a JSON configuration file for the demo.
Read JSON configuration file
JSON is our common configuration file format, which can be very intuitive to reflect the configuration file hierarchy.
Create a new. NET Core console application and add a file to the project with appsettings.json
the following file contents:
{ "Name": "Jerry", "option1": "value1_from_json", "option2": 2, "subsection": { "suboption1": "subvalue1_from_json" }, "wizards": [ { "Name": "Gandalf", "Age": "1000" }, { "Name": "Harry", "Age": "17" } ]}
Add the Microsoft.Extensions.Configuration.Json
reference, and then use the following code to create the Iconfiguartion object:
public static IConfiguration Configuration { get; set; }//构建Configurationvar builder = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json");Configuration = builder.Build();
Use the Iconfiguartion object to obtain configuration information:
static void ReadConfiguration(){ Console.WriteLine($"Name = {Configuration["Name"]}"); 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();}
To read configuration information using strongly typed:
static void ConvertConfiguration(){ //读取整个配置文件 var appSettings = Configuration.Get<AppSettings>(); Console.WriteLine("AppSettings = "); Console.WriteLine(JsonConvert.SerializeObject(appSettings, Formatting.Indented)); //读取某个节点 IList<Wizard> wizards = Configuration.GetSection("wizards").Get<IList<Wizard>>(); Console.WriteLine("wizards = "); Console.WriteLine(JsonConvert.SerializeObject(wizards, Formatting.Indented)); Console.WriteLine("Press a key..."); Console.ReadKey();}
Note: Using the Bind method conversion in version 1.0, 2.0 can use the Get method to obtain strongly typed files more easily = =
Note: When multiple profiles are used and the same key is included in the configuration file, the key values in the added configuration file will overwrite the first added value = =
Other types of configuration files are used similarly, not to repeat them.
Reference Document: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/startup?view=aspnetcore-2.1
. NET core usage configuration files