1.使用Configuration直接读
构造函数中添加 IConfiguration
private readonly IConfiguration config;
public WeatherForecastController(IConfiguration _config)
{
this.config = _config;
}
appsettings.json文件中代码格式:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
在控制器中添加如下代码:
var str = config["Logging:LogLevel:Default"];
2.使用ConfigurationRoot读取
appsettings.json文件内容
注意:json文件属性设置为 如果较新则复制
{
"name": "Hpf",
"age": 18,
"proxy": {
"address": "aa",
"port": "80"
}
}
ConfigSetup配置类
public static class ConfigSetup
{
private static IConfigurationRoot _configroot;
public static IConfigurationRoot Configroot
{
get
{
if (_configroot == null)
{
var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
_configroot = builder.Build();
}
return _configroot;
}
set { _configroot = value; }
}
}
使用方法一:
string name1 = ConfigSetup.Configroot["name"];
string address1 = ConfigSetup.Configroot.GetSection("proxy:address").Value;
使用方法二(映射为类):
class Proxy
{
public string Address { get; set; }
public int Port { get; set; }
}
Proxy proxy = ConfigSetup.Configroot.GetSection("proxy").Get<Proxy>();
string address = proxy.Address;
3.不同类型数据的读取的方式
Json配置文件模拟数据
{
"name": "Hpf",
"age": 18,
"proxy": {
"address": "aa",
"port": "80",
"ids": [ 1, 3, 5 ]
}
}
读取某一个变量的值
ConfigSetup.Configroot["name"]
读取多层级下某一个变量的值
ConfigSetup.Configroot["proxy:address"]
or
ConfigSetup.Configroot.GetSection("proxy:address").Value
读取数组
ConfigSetup.Configroot["proxy:ids:0"]
or
ConfigSetup.Configroot.GetSection("proxy:ids:0").Value
某一层级下多个变量转成对象读取
Proxy proxy = ConfigSetup.Configroot.GetSection("proxy").Get<Proxy>();