一、比如appsettings.json里面有这样一段代码
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ErpConnection": "server=192.111.1.1;database=Erp;uid=sa;pwd=123;MultipleActiveResultSets=true;"
}
}
二、在Startup 类中,我们需要读取 数据库连接字符串 ErpConnection,可以这样
public class Startup
{
//注入配置类
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Dbs.Models.ErpContext>(options =>
{
//2种方法都可以连接数据库
//方法1:直接通过 GetConnectionString 方法获取节点
//options.UseSqlServer(Configuration.GetConnectionString("ErpConnection"));
//方法2:通过GetSection 一级一级获取节点
//options.UseSqlServer(Configuration.GetSection("ConnectionStrings").GetSection("ErpConnection").Value);
options.UseSqlServer(Configuration.GetSection("ConnectionStrings:ErpConnection").Value);
}, ServiceLifetime.Transient);
}
}
三、使用GetSection()获取复杂的值
比如我们在appsettings.json中有这样一段配置
{
"AppConnectionStrings": {
"PathPrefix": "",
"Something": "Something context",
"Clients": { "line": "longclients" }
}
}
如果我们想要获取Clients的值,我们可能会这样操作
var clients = Configuration.GetSection("AppConnectionStrings:Clients").Value;
结果返回的 clients 是null。
其实我们正确的做法是这样的:
1、我们要根据json的数据格式创建相应的类
public class AppConnectionStrings
{
public string PathPrefix { get; set; }
public string Something { get; set; }
public Clients Clients { get; set; }
}
public class Clients
{
public string line { get; set; }
}
2、将Options服务添加到服务集合并从配置中加载设置
public void ConfigureServices(IServiceCollection services)
{
// This is only required for .NET Core 2.0
services.AddOptions();
services.Configure<AppConnectionStrings>(Configuration.GetSection("AppConnectionStrings"));
services.AddMvc();
}
注:也可以通过指定要加载的配置部分来加载方法中的子选项
services.Configure<Clients>(Configuration.GetSection("AppConnectionStrings:Clients");
3、控制器中我们可以通过构造函数注入IOptions<Clients>
来读取
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly AppConnectionStrings _settings;
public TestController(IOptions<AppConnectionStrings> settings)
{
_settings = settings.Value;
}
[Route("GetAppConnectionStrings")]
[HttpGet]
public ActionResult<JObject> GetAppConnectionStrings()
{
return JObject.FromObject( _settings);
}
}
我们请求GetAppConnectionStrings接口的时候,就得到相应配置数据
注:使用前一定要先在Startup 类中注入服务services.Configure<AppConnectionStrings>(Configuration.GetSection("AppConnectionStrings"));
没有这一步,读取不了数据: