栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > asp

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

asp 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/54926.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号