我是靠谱客的博主 悲凉帅哥,这篇文章主要介绍.net core 静态类获取appsettings的方法,现在分享给大家,希望可以做个参考。

注入获取

注入获取通过IConfiguration直接获取的方法官方文档里就有,可以直接看这里

如:appsettings.json

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{ "Position": { "Title": "编辑器", "Name": "Joe Smith" }, "MyKey": "My appsettings.json Value", "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Lifetime": "Information" } }, "AllowedHosts": "*" }

可以用注入的IConfiguration,用冒号分隔的形式取值,如下

复制代码
1
var name = Configuration["Position:Name"];

实体类获取

单个获取对应多个组合的值就不太方便,比如Logging最好能用一个类类直接接收,方法如下:
先定义一个跟json节点对应的类

复制代码
1
2
3
4
5
6
7
8
9
10
public class Logging { public LogLevel LogLevel { get; set; } } public class LogLevel { public string Default { get; set; } public string Microsoft { get; set; } public string Lifetime { get; set; } }

然后在Startup的里ConfigureServices增加

复制代码
1
services.Configure<Logging>(Configuration.GetSection("Logging"));

调用的地方直接注入

复制代码
1
2
3
4
5
private readonly Logging _config; public HomeController(IOptions<Logging> config) { _config = config.Value; }

静态类获取

如果是在静态类里使用,可以在Startup里的构造函数中这样写

复制代码
1
2
3
4
5
public Startup(IConfiguration configuration) { Configuration = configuration; configuration.GetSection("Logging").Bind(MySettings.Setting); }

使用IConfigurationSection的Bind方法将节点直接绑定至一个实例上,注意示例必须是初始化过的。

复制代码
1
2
3
4
public static class MySettings { public static Logging Setting { get; set; } = new Logging(); }

有了静态类的属性在在静态类里就可以使用了。

到此这篇关于.net core 静态类获取appsettings的方法的文章就介绍到这了,更多相关.net core获取appsettings内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是悲凉帅哥最近收集整理的关于.net core 静态类获取appsettings的方法的全部内容,更多相关.net内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(134)

评论列表共有 0 条评论

立即
投稿
返回
顶部