1. 程式人生 > 程式設計 >.net core 靜態類獲取appsettings的方法

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

有了靜態類的屬性在在靜態類裡就可以使用了。

到此這篇關於.net core 靜態類獲取appsettings的方法的文章就介紹到這了,更多相關.net core獲取appsettings內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!