亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

.net core 靜態(tài)類獲取appsettings的方法

 更新時間:2020年06月25日 09:11:29   作者:古道  
這篇文章主要介紹了.net core 靜態(tài)類獲取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節(jié)點對應的類

 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;
 }

靜態(tài)類獲取

如果是在靜態(tài)類里使用,可以在Startup里的構造函數中這樣寫

public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
      configuration.GetSection("Logging").Bind(MySettings.Setting);
    }

使用IConfigurationSection的Bind方法將節(jié)點直接綁定至一個實例上,注意示例必須是初始化過的。

public static class MySettings
  {
    public static Logging Setting { get; set; } = new Logging();
  }

有了靜態(tài)類的屬性在在靜態(tài)類里就可以使用了。

到此這篇關于.net core 靜態(tài)類獲取appsettings的方法的文章就介紹到這了,更多相關.net core獲取appsettings內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論