• .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();
        }
    

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

  • 相关阅读:
    SVN服务器搭建和使用(二)
    SVN服务器搭建和使用(一)
    【CentOs】配置nginx
    【CentOs】sudo使用
    【CentOS】搭建Web服务器
    【CentOS】搭建git服务器
    【Python】内置数据类型
    【Python】Eclipse和pydev搭建Python开发环境
    【Python】一个简单的例子
    【Python】vim7.4 配置python2.6支持Gundo
  • 原文地址:https://www.cnblogs.com/gudao119/p/13190084.html
Copyright © 2020-2023  润新知