The configuration of the Dotnetcore program is no longer completely limited to XML files, adding a more general JSON configuration.
The class that reads the JSON configuration file is primarily Microsoft.Extensions.Configuration
under the namespace, and after the corresponding program is created, NuGet
the DLL file is introduced when needed.
1. Create a ConsoleApp program
In Vs2017, select Create Console App (. NET Core) directly using the new item.
2. Use NuGet to add program references
On the Dependencies node, right-click, select Manage NuGet packages, search Microsoft.Extensions.Configuration
, click Install, Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Binder
Microsoft.Extensions.Configuration.Json
3. Create a JSON configuration file
Create a new file, select "JavaScript JSON configuration file", and configure the file Properties 复制到输出目录
property to 如果较新则复制
, and enter the following configuration information in the file
{ "General":{ "UseLED":true, "UseScan":false, "PortName":"Port1", "PortRate":9600 }}
The General
configuration section includes four configurations, as listed in the example:
Useled, Usescan, PortName, portrate
。 You can also add more configuration information or configuration sections under the configuration section, or you can add more of the same level configuration section information.
4. Create a configuration class
Create a corresponding configuration class based on the structure of the configuration file:
public class GeneralSetting { public bool UseLED { get; set; } public bool UseScan { get; set; } public int PortRate { get; set; } public string PortName { get; set; } }
The name of the property in the configuration class is not sensitive to the case of the configuration item in the JSON configuration file and must match the full text.
5. Read the configuration and bind to the configuration class instance
Dotnetcore reads the JSON file and binds the class and method to the corresponding class instance under the namespace Microsoft.Extensions.Configuration
.
var builder = new ConfigurationBuilder().AddJsonFile("appsetting.json");var configuration =builder.Build();GeneralSetting setting = new GeneralSetting();configuration.GetSection("General").Bind(setting);
With the code above, you can assign the configuration information in the configuration file to the configuration class instance.
Dotnetcore Learning-1. Read the JSON configuration and bind to the configuration class instance