asp.net core项⽬默认的配置⽂件是appsettings.json,创建项⽬时就会⾃动⽣成这个文件,我们可以将⼀些配置信息存放在这个配置⽂件中,这样做的好处是当我们修改配置⽂件 时,不在需要重启应⽤,可以实现热更新。
{ "logging": { "loglevel": { "default": "information", "microsoft.aspnetcore": "warning" } }, "allowedhosts": "*", "msg": "hello world" }
iconfiguration
个路由终结点来演⽰如何读取这个配置
app.mapget("config", (iconfiguration configuration) => { return configuration["msg"] + "_" + configuration["logging:loglevel:default"]; });
通过ioc注⼊iconfiguration对象,我们就可以访问不同节点的配置了,如果是单层节点, 通过configuration[“msg”]的⽅式进⾏访问,如果是多层级,则通过 configuration[“logging:loglevel:default”]来访问
通过getvalue方法获取
app.mapget("config", (iconfiguration configuration) => { return configuration.getvalue<string>("msg"); });
getvalue⽆法读取对象,会报异常
通过getsection方法获取
app.mapget("config", (iconfiguration configuration) => { return configuration.getsection("msg").value; });
读取对象
app.mapget("config", (iconfiguration configuration) => { return configuration.getsection("person").get<person>(); });
使用委托来配置选项
先定义⼀个实体:
public class person { public string name { get;set; } public int age { get;set; } }
配置如下:
"person": { "name": "张三", "age": 18 }
注册配置:
builder.services.configure<person> (builder.configuration.getsection("person"));
使⽤配置:
app.mapget("config", (ioptions<person> options) => { return $"{options.value.name},{options.value.age}"; });
到此这篇关于asp.net读取配置文件的多种方式详解的文章就介绍到这了,更多相关asp.net读取配置文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论