Google Code Prettify

[NET Core] 如何讀取 appsettings.json 組態設定檔

 .NET Core App 讀取 Json 設定檔


安裝

Install-Package Microsoft.Extensions.Configuration.Json


讀取設定檔步驟

通過 IConfigurationBuilder 物件建立 IConfigurationRoot 物件。

IConfigurationBuilder.SetBasePath 方法是設定檔案的基本路徑

IConfigurationBuilder.AddJsonFile 方法是讀取設定檔的路徑,完整的路徑為 基本路徑 + AddJsonFile

IConfigurationRoot[節點名稱] / IConfiguration[節點名稱] 取得設定值



[TestMethod]
public void 讀取設定檔()
{
    var builder = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json");
    var config = builder.Build();

    Console.WriteLine($"AppId = {config["AppId"]}");
    Console.WriteLine($"AppId = {config["Player:AppId"]}");
    Console.WriteLine($"Key = {config["Player:Key"]}");
    Console.WriteLine($"Connection String = {config["ConnectionStrings:DefaultConnectionString"]}");
}  
  



參數綁定強型別 安裝 Install-Package Microsoft.Extensions.Configuration.Binder 

public class AppSetting
{ 
    public ConnectionStrings ConnectionStrings { get; set; }
 
    public Player Player { get; set; }
}

public class Player
{
    public string AppId { get; set; }

    public string Key { get; set; }
}
 

ConfigurationBinder.Bind/Get擴充方法,直接將 IConfiguration 轉換成強型別物件
 
[TestMethod]
public void 綁定設定_擴充方法_Get()
{
    var builder = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json");
    var config     = builder.Build();
    var player = config.GetSection("Player").Get();
    Console.WriteLine($"AppId = {player.AppId}");
    Console.WriteLine($"Key = {player.Key}");
}
 

[TestMethod]
public void 綁定設定_擴充方法_Bind()
{
    var builder = new ConfigurationBuilder()
                  .SetBasePath(Directory.GetCurrentDirectory())
                  .AddJsonFile("appsettings.json");
    var config     = builder.Build();
    var appSetting = new AppSetting();
    config.Bind(appSetting);
    Console.WriteLine($"AppId = {appSetting.Player.AppId}");
    Console.WriteLine($"Key = {appSetting.Player.Key}");
    Console.WriteLine($"Connection String = {appSetting.ConnectionStrings.DefaultConnectionString}");
}