ASP.NET Core 6 讀取設定檔(appsettings.json)範例

在 ASP.NET Core 6 中,預設的設定檔是使用放在專案資料夾內的 appsettings.json 檔案。預設已經有儲存 Log 紀錄層級和主機過濾的兩組設定資訊,預設設定內容如下:
	
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
    

appsettings.json 不只用來儲存上述的兩個預設資訊, 通常也會用來儲存資料庫連接資訊、 SSL 憑証的路徑等可能會頻繁修改, 或是帳號密碼之類的不方便寫死在程式碼中的資訊。

多設定檔介紹

平時在開發時可能會在不同的環境上切換,我們可以透過使用多組設定檔,並在執行時附加參數來快速切換不同的設定檔。

在專案建立完成後就已經會有 appsettings.json 和 appsettings.Development.json (開發環境)兩組設定檔了,通常會將開發時的資訊寫在 appsettings.Development.json 設定檔中,當然也可以再自行增加多個設定檔,只要檔名符合 appsettings.{Environment}.json 即可,例如正式環境的設定檔名稱通常就會命名為 appsettings.Production.json

在執行時只要附加 ASPNETCORE_ENVIRONMENT 參數並指定名稱即可,例如要使用 appsettings.Development.json 設定檔則可以附加下面的這個參數:
    
ASPNETCORE_ENVIRONMENT=Development
    

在讀取時會優先讀取 appsettings.json 設定檔裡的內容,然後再將 appsettings.Development.json 讀取到有重複的內容覆蓋過去。

讀取設定值

只要在 Program.cs 中做好依賴注入(Dependency Injection, DI)的類別就可以很簡單的透過自動注入 IConfiguration 來取得設定檔。

我們先在設定檔中新增一些內容方便測試:
	
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "key": "value",
  "keys": {
    "key1": "test-key1",
    "key2": "test-key2"
  },
  "AllowedHosts": "*"
}
    


在建立 ASP.NET Core API 專案時會自動產生 WeatherForecastController.cs 這個檔案,本次示範就先直接在這個檔案中做示範,系統自動產生的預設內容如下:
 

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}
    

增加讀取設定檔後的完整程式碼如下:
	 

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IConfiguration _configuration;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
    {
        _logger = logger;
        _configuration = configuration;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        string logLevelDefault = _configuration["Logging:LogLevel:Default"];
        _logger.LogInformation($"Default: {logLevelDefault}"); // Default: Information

        _logger.LogInformation($"key: {_configuration["key"]}"); // key: value

        var key = _configuration.GetSection("keys").Get<Dictionary<string, string>>();
        foreach (var value in key)
        {
            _logger.LogInformation($"key: {value.Key}, value: {value.Value}");

            // key: key1, value: test-key1
            // key: key2, value: test-key2
        }

        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
    }
}
    

讀取的內容包含單純字串、讀取鍵值對應的 Dictionary 還有多層內的設定值

延伸閱讀:
ASP.NET Core 使用強型別讀取設定檔 appsettings.json 教學
ASP.NET Core 7 啟動時驗證設定檔(appsettings.json)內容
ASP.NET Core 6 使用 yaml 檔案取代預設的 appsettings.json 設定檔

參考資料:
Configuration in ASP.NET Core

留言