appsettings.json文件
在appsettings.json
中配置参数:
{
"ConnectionStrings": {
"Default": "Server=.; Database=demoDb; Trusted_Connection=True;"
},
"AllowedHosts": "*"
}
获取数据库连接字符串
GetConnectionString
public Startup(IConfiguration configuration)
{
var defaultConnectionString = configuration.GetConnectionString("Default");
}
获取参数
GetSection
返回键值对对象。
public Startup(IConfiguration configuration)
{
var allowedHosts = configuration.GetSection("AllowedHosts").Value;
}
GetValue
返回泛型类型。
public Startup(IConfiguration configuration)
{
var allowedHosts = configuration.GetValue<string>("AllowedHosts");
}
KeyValue
返回string
类型。
public Startup(IConfiguration configuration)
{
var allowedHosts = configuration["AllowedHosts"];
}
手动初始化IConfiguration
可以用于单元测试项目,手动初始化IConfiguration
。
需要添加程序集:
Install-Package Microsoft.Extensions.Configuration.Abstractions
Install-Package Microsoft.Extensions.Configuration.Json
需要添加引用:
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
var configuration = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json" })
.Build()
// 指定基路径
var configuration = new ConfigurationBuilder()
.SetBasePath(System.Environment.CurrentDirectory.Split("bin")[0])
.Add(new JsonConfigurationSource { Path = "appsettings.json" })
.Build();
网友评论