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

所属分类: 网络编程 / ASP.NET 阅读数: 2027
收藏 0 赞 0 分享

注入获取

注入获取通过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();
  }

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

更多精彩内容其他人还在看

Asp.net中的mail的发送

Asp.net中的mail的发送
收藏 0 赞 0 分享

用ASP.Net实现文件的在线压缩和解压缩

用ASP.Net实现文件的在线压缩和解压缩
收藏 0 赞 0 分享

ASP.NET中文件上传下载方法集合

ASP.NET中文件上传下载方法集合
收藏 0 赞 0 分享

ASP.NET通过Remoting service上传文件

ASP.NET通过Remoting service上传文件
收藏 0 赞 0 分享

ASP.NET2.0服务器控件之Render方法

ASP.NET2.0服务器控件之Render方法
收藏 0 赞 0 分享

ASP.NET2.0 WebRource,开发微调按钮控件

ASP.NET2.0 WebRource,开发微调按钮控件
收藏 0 赞 0 分享

ASP.NET2.0新特性概述

ASP.NET2.0新特性概述
收藏 0 赞 0 分享

介绍几个ASP.NET中容易忽略但却很重要的方法函数

介绍几个ASP.NET中容易忽略但却很重要的方法函数
收藏 0 赞 0 分享

asp.net2.0如何加密数据库联接字符串

asp.net2.0如何加密数据库联接字符串
收藏 0 赞 0 分享

用.NET 2.0压缩/解压功能处理大型数据

用.NET 2.0压缩/解压功能处理大型数据
收藏 0 赞 0 分享
查看更多