ASP.NET Core项⽬默认的配置⽂件是appsettings.json,创建项⽬时就会⾃动⽣成这个文件,我们可以将⼀些配置信息存放在这个配置⽂件中,这样做的好处是当我们修改配置⽂件 时,不在需要重启应⽤,可以实现热更新。
1 2 3 4 5 6 7 8 9 10 | { "Logging" : { "LogLevel" : { "Default" : "Information" , "Microsoft.AspNetCore" : "Warning" } }, "AllowedHosts" : "*" , "msg" : "hello world" } |
IConfiguration
个路由终结点来演⽰如何读取这个配置
1 2 3 4 5 | app.MapGet( "config" , (IConfiguration configuration) => { return configuration[ "msg" ] + "_" + configuration[ "Logging:LogLevel:Default" ]; }); |
通过IOC注⼊IConfiguration对象,我们就可以访问不同节点的配置了,如果是单层节点, 通过configuration[“msg”]的⽅式进⾏访问,如果是多层级,则通过 configuration[“Logging:LogLevel:Default”]来访问
通过GetValue方法获取
1 2 3 4 | app.MapGet( "config" , (IConfiguration configuration) => { return configuration.GetValue( "msg" ); }); |
GetValue⽆法读取对象,会报异常
通过GetSection方法获取
1 2 3 4 | app.MapGet( "config" , (IConfiguration configuration) => { return configuration.GetSection( "msg" ).Value; }); |
读取对象
1 2 3 4 | app.MapGet( "config" , (IConfiguration configuration) => { return configuration.GetSection( "Person" ).Get(); }); |
使用委托来配置选项
先定义⼀个实体:
1 2 3 4 5 | public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } |
配置如下:
1 2 3 4 | "Person" : { "Name" : "张三" , "Age" : 18 } |
注册配置:
1 2 | builder.Services.Configure (builder.Configuration.GetSection( "Person" )); |
使⽤配置:
1 2 3 4 | app.MapGet( "config" , (IOptions options) => { return $ "{options.Value.Name},{options.Value.Age}" ; }); |
到此这篇关于ASP.NET读取配置文件的多种方式详解的文章就介绍到这了,更多相关ASP.NET读取配置文件内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!