[TOC] Aso.Net Core 的配置系統Configuration 1.以前的配置文件格式為XML 2.新版的配置文件格式支持 { json ,xml, ini, memory, command, env..... } 01.Json文件的弱類型方式讀取 1. Json文件 【Mic ...
目錄
Aso.Net Core 的配置系統Configuration
1.以前的配置文件格式為XML
2.新版的配置文件格式支持 { json ,xml, ini, memory, command, env..... }
01.Json文件的弱類型方式讀取
Json文件 【Microsoft.Extensions.Configuration.Json】
添加配置文件json文件,並設置內容
{ "DataBase": { "SqlServer": { "ConnectionString": "server=.;database=testdb;uid=sa;pwd=123;" }, "MySql": { "IpAddress": "127.0.0.1", "port": 3306 } }, "endArray": [ { "endId": 20 }, { "endId": "30" } ] }
獲取數據
private static void Main(string[] args) { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Environment.CurrentDirectory) .AddJsonFile("AppSettings.json",true,true) .AddInMemoryCollection() .Build(); var str1 = configuration["DataBase:SqlServer:ConnectionString"]; var str2 = configuration["endArray:0:endId"]; Console.WriteLine($"{str1}+---{str2}"); }
02.Json文件的強類型獲取方式
1.添加引用【Microsoft.Extensions.Configuration.Binder】
2.GetValue方式獲取
private static void Main(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("AppSettings.json",true,true)
.AddInMemoryCollection()
.Build();
//GetValue獲取方式
int val = configuration.GetValue<int>("endArray:0:endId");
Console.WriteLine(val);
}
3.實體映射方式
private static void Main(string[] args)
{
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("AppSettings.json",true,true)
.AddInMemoryCollection()
.Build();
//Bind 獲取方式
Root root=new Root();
configuration.Bind(root);
var ip = root.DataBase.MySql.IpAddress;
var entid = root.endArray[0].endId;
Console.WriteLine($"{ip}{entid}");
//Get<T> 獲取
var root = configuration.Get<Root>();
var ip = root.DataBase.MySql.IpAddress;
var entid = root.endArray[0].endId;
Console.WriteLine($"{ip}{entid}");
}
//這裡是實體類
public class SqlServer
{
/// <summary>
///
/// </summary>
public string ConnectionString { get; set; }
}
public class MySql
{
/// <summary>
///
/// </summary>
public string IpAddress { get; set; }
/// <summary>
///
/// </summary>
public int port { get; set; }
}
public class DataBase
{
/// <summary>
///
/// </summary>
public SqlServer SqlServer { get; set; }
/// <summary>
///
/// </summary>
public MySql MySql { get; set; }
}
public class EndArray
{
/// <summary>
///
/// </summary>
public int endId { get; set; }
}
public class Root
{
/// <summary>
///
/// </summary>
public DataBase DataBase { get; set; }
/// <summary>
///
/// </summary>
public List<EndArray> endArray { get; set; }
}