第一种使用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>();
本文详细介绍了在ASP.NET Core中如何使用IConfiguration接口来读取配置文件,包括设置日志级别、允许主机和连接字符串等。同时,讲解了通过IOptions模式进行配置注入的方法,以及如何从类库中读取JSON配置文件。文章还展示了如何在Startup类中配置服务,并创建与配置节结构相同的实体类来获取配置值。

626

被折叠的 条评论
为什么被折叠?



