ASP.NET Core 使用強型別讀取設定檔 appsettings.json 教學

在上一篇:ASP.NET Core 6 讀取設定檔範例 中有示範使用 IConfiguration 的方式讀取設定檔,不過缺點就是是 Key, Value 的形式讀取,每次取得都要使用 Key,是很方便沒錯,但若資料一多就容易出錯,就會讀取不到資料。

假設我們要建立一個附件相關的設定值資訊儲存於設定檔中,
    
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Attachment": {
    "Path": "D:\\Attachment",
    "MaxSize": 1024,
    "MaxCount": 10,
    "Extensions": [
      ".jpg",
      ".png",
      ".gif",
      ".bmp",
      ".jpeg"
    ]
  }
}
    

只要依照設定值名稱建立相對應的物件:
    
public class AttachmentOptions
{
    public string Path { get; set; } = string.Empty;
    public string MaxSize { get; set; } = string.Empty;
    public string MaxCount { get; set; } = string.Empty;
    public List<string> Extensions { get; set; } = new();
}
    

在 Program.cs 中注入:
    
builder.Services.Configure<AttachmentOptions>( builder.Configuration.GetSection("Attachment"));
    

就可以很容易的讀取到資料了:
    
[ApiController]
[Route("[controller]")]
public class RuyutController : ControllerBase
{
    private readonly AttachmentOptions _options;

    public RuyutController(IOptions<AttachmentOptions> options)
    {
        _options = options.Value;
    }

    [HttpGet]
    public string Get()
    {
        Console.WriteLine($"Path: {_options.Path}");
        Console.WriteLine($"MaxSize: {_options.MaxSize}");
        Console.WriteLine($"MaxCount: {_options.MaxCount}");
        Console.WriteLine($"Extensions:");
        _options.Extensions.ForEach(Console.WriteLine);

        return _options.Path;
    }
}
    

範例輸出:
    
C:\Attachment
1024
10
.jpg
.png
.gif
.bmp
.jpeg
    

在 cshtml 中讀取設定值

有時候就會遇到要在 cshtml 中讀取,也非常簡單,使用 inject 注入即可:
    
@using Microsoft.AspNetCore.Mvc.TagHelpers
@using Microsoft.Extensions.Options
@inject IOptions<AttachmentOptions> Options

<h2>@Options.Value.Path</he>
    


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

參考資料:
Options pattern in ASP.NET Core

留言