您现在的位置是:网站首页> 编程资料编程资料
.net core 静态类获取appsettings的方法_实用技巧_
2023-05-24
357人已围观
简介 .net core 静态类获取appsettings的方法_实用技巧_
注入获取
注入获取通过IConfiguration直接获取的方法官方文档里就有,可以直接看这里
如:appsettings.json
{ "Position": { "Title": "编辑器", "Name": "Joe Smith" }, "MyKey": "My appsettings.json Value", "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Lifetime": "Information" } }, "AllowedHosts": "*" } 可以用注入的IConfiguration,用冒号分隔的形式取值,如下
var name = Configuration["Position:Name"];
实体类获取
单个获取对应多个组合的值就不太方便,比如Logging最好能用一个类类直接接收,方法如下:
先定义一个跟json节点对应的类
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增加
services.Configure(Configuration.GetSection("Logging"));
调用的地方直接注入
private readonly Logging _config; public HomeController(IOptionsconfig) { _config = config.Value; }
静态类获取
如果是在静态类里使用,可以在Startup里的构造函数中这样写
public Startup(IConfiguration configuration) { Configuration = configuration; configuration.GetSection("Logging").Bind(MySettings.Setting); } 使用IConfigurationSection的Bind方法将节点直接绑定至一个实例上,注意示例必须是初始化过的。
public static class MySettings { public static Logging Setting { get; set; } = new Logging(); } 有了静态类的属性在在静态类里就可以使用了。
到此这篇关于.net core 静态类获取appsettings的方法的文章就介绍到这了,更多相关.net core获取appsettings内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关内容
- 在VS2009中集成自动上传nuget包到服务器的解决方案_实用技巧_
- asp.net core常见的4种数据加密算法_实用技巧_
- ASP.NET Core对Controller进行单元测试的完整步骤_实用技巧_
- .net EF Core专题:EF Core 读取数据时发生了什么?_实用技巧_
- .Net 对于PDF生成以及各种转换的操作_实用技巧_
- 详解asp.net core 依赖注入_基础应用_
- asp.net core 修改默认端口的几种方法_实用技巧_
- ASP.NET Core MVC如何实现运行时动态定义Controller类型_实用技巧_
- xUnit 编写 ASP.NET Core 单元测试的方法_实用技巧_
- 聊一聊Asp.net过滤器Filter那一些事_实用技巧_
