第一种使用IConfiguration
Configuration["Logging:LogLevel:Microsoft"] // Warning
Configuration["AllowedHosts"] // *
Configuration["ConnectionStrings:ReaderStrings:0"] // this is test
第二种使用IOptions
首先在Startup类ConfigureServices方法中添加 services.Configure<GetJsonValue>(Configuration.GetSection("ConnectionStrings"));
其中GetJsonValue是个实体类,与GetSection("ConnectionStrings")中ConnectionStrings结构一样,如下图:
然后注入
使用
从类库中读取json配置文件:
首先 引用 Microsoft.Extensions.Configuration 和 Microsoft.Extensions.Configuration.Json 软件包
添加如下代码:
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
// 像在每个web项目中一样使用配置
var myOptions = configuration.GetSection("MyOptions").Get<MyOptions>();