.net core 配置包括很多種 例如內存變量、命令行參數、環境變量以及物理文件配置和自定義配置
物理文件配置主要有三種,它們分別是JSON、XML和INI,對應的配置源類型分別是JsonConfigurationSource、XmlConfigurationSource和IniConfigurationSource 這里主要講JSON的配置
讀取配置文件
{
"AllowedHosts": "*",
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
"Arry": [ { "Name": "zhangsan" }, { "Name": "lisi" }, { "Name": "wangwu" } ]
}
1.使用Key讀取
Configuration["AllowedHosts"]; // 結果 *
Configuration["Logging:IncludeScopes"]; // 結果 false
Configuration["Logging:LogLevel:Default"]; // 結果 Warning
Configuration["Arry:0:Name"]; // 結果 zhangsan
小結:讀取嵌套的配置,使用冒號隔開;讀取數組形式的配置,使用數組的下標索引,0表示第一個。
2.使用GetValue<T>
Configuration.GetValue<string>("AllowedHosts"); // 結果 *
Configuration.GetValue<bool>("Logging:IncludeScopes"); // 結果 false
小結:GetValue方法的泛型形式還有一個GetValue("key",defaultValue)重載。如果key的配置不存在,則為指定的默認值。
3.使用Options
配置文件
{
"Name": "zhangsan",
"Age": 22,
"Company",{
"Id":1,
"Address":"中國 北京"
}
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
public class Company
{
public int Id {get;set;}
public string Address{get;set;}
}
}
注入:
services.Configure<User>(Configuration);
services.Configure<Company>(Configuration.GetSection("Company"));
services.Configure<Company>(Configuration.GetSection("User:Company"));
讀取:
構造函數讀取
private readonly User _user; public GetConfig(IOptions<User> _o
ptions
)
{ _user = _option.Value; }
ServiceProvider讀取 serviceProvider.GetService<IOptions<User>>().Vlaue
4.使用Bind
var user = new User(); Configuration.Bind(user);
var company=new Company();Configuration.GetSection("Conpany").Bind(company);
4.使用Get<T>
var user = Configuration.Get<User>();或者var commpany = Configuration.GetSection("Company").Get<Company>();