如何获取 appsettings.json 里的值
作者:互联网
一、比如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,public,获取,json,ConnectionStrings,Configuration,options,Er 来源: https://www.cnblogs.com/qingheshiguang/p/14316472.html