.net core 静态类获取appsettings的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

.net core 静态类获取appsettings的方法

古道   2020-06-25 我要评论

本文着重讲解了.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<Logging>(Configuration.GetSection("Logging"));

调用的地方直接注入

 private readonly Logging _config;
 public HomeController(IOptions<Logging> config)
 {
   _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();
  }

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们