IConfiguration
1、在appsettings.json文件添加配置
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Id": "123456",
"Name": "KK老师",
"TechInfo": {
"Id": 123456,
"Name": "KK001"
},
"ConnectionStrings": {
"WriteConnection": "Server=LAPYUIU(DEJP1;DataBase=demo1;Trusted_Connection=True;",
"ReadConnectionList": [
"Server=LAPYUIU(DEJP1;DataBase=demo01;Trusted_Connection=True;",
"Server=LAPYUIU(DEJP1;DataBase=demo02;Trusted_Connection=True;",
"Server=LAPYUIU(DEJP1;DataBase=demo03;Trusted_Connection=True;"
]
},
"iocConfig": "IOCPTOP-JU"
}
2、获取配置文件中配置信息三大方法
1)常规
Program.cs中:
string? id = builder.Configuration["Id"];
string? name = builder.Configuration.GetValue<string>("Name");
Controller中:
private readonly IConfiguration _config;
public A02ConfigController(IConfiguration config)
{
_config = config;
}
public IActionResult Index()
{
string? id = _config.GetValue<string>("id");
string? name = _config["Name"];
return View(id);
}
2)新建类并绑定
根据下面配置文件内容新建类:
"ConnectionStrings": {
"WriteConnection": "Server=LAPYUIU(DEJP1;DataBase=demo1;Trusted_Connection=True;",
"ReadConnectionList": [
"Server=LAPYUIU(DEJP1;DataBase=demo01;Trusted_Connection=True;",
"Server=LAPYUIU(DEJP1;DataBase=demo02;Trusted_Connection=True;",
"Server=LAPYUIU(DEJP1;DataBase=demo03;Trusted_Connection=True;"
]
},
ConnectionStrings.cs
public class ConnectionStrings
{
public string? WriteConnection { get; set; }
public List<string>? ReadConnectionList { get; set; }
}
得到配置信息
//Programs.cs中
//ConnectionStrings options = new ConnectionStrings();
//builder.Configuration.Bind("ConnectionStrings", options);
ConnectionStrings options = new ConnectionStrings();
_config.Bind("ConnectionStrings", options);
string? s = options.WriteConnection;
string? s1 = options.ReadConnectionList[0];
string? s2 = options.ReadConnectionList[1];
string? s3 = options.ReadConnectionList[2];
3)通过IServiceCollection配置, Program.cs中自动完成配置信息映射到和配置文件相同格式的实体中去
同2)需要先新建类ConnectionStrings.cs
然后再Program.cs中添加如下代码:
builder.Services.Configure<ConnectionStrings>(builder.Configuration.GetSection("ConnectionStrings"));
Controller中使用(IOptionsMonitor和IOptions均可以使用):
private readonly ConnectionStrings _ConnectionStrings;
private readonly ConnectionStrings _Options;
public A02ConfigController(IOptionsMonitor<ConnectionStrings> optionsMonitor, IOptions<ConnectionStrings> options)
{
_ConnectionStrings = optionsMonitor.CurrentValue;
_Options = options.Value;
}
public IActionResult Index()
{
string? s1 = _Options.WriteConnection;
List<string>? l1 = _ConnectionStrings.ReadConnectionList;
return View();
}