---
# System prepended metadata

title: '[.NET 筆記 012] .NET 強型別設定：Options Pattern 與 Configuration Binder'

---

## [.NET 筆記 012] .NET 強型別設定：Options Pattern 與 Configuration Binder

###### 📅 2026-04-29

### 📌 何謂 .NET 強型別設定？
.NET 強型別設定 (Strongly Typed Configuration)：
「將設定資料（如 appsettings.json）轉換為具有明確型別的 C# 類別，
並透過「Options Pattern + DI」：安全、可維護地存取與使用的機制。」

### 📌 .NET 強型別設定的步驟
```
1. 讀設定檔
appsettings.json → IConfiguration

2. 綁定為強型別物件
Configuration Binder：
負責把設定資料（JSON / IConfiguration）轉成 class（強型別物件）

3. 設定管理與使用
Options Pattern：
負責將設定註冊到 DI，並提供統一存取方式
（IOptions<T> / IOptionsSnapshot<T> / IOptionsMonitor<T>）
最後，在 Service / Controller 使用 (DI = 依賴注入 = Dependency Injection)
```

---

### 📌 Step-0(a). 開啟專案
承接上一篇 [[.NET 筆記 011]](https://hackmd.io/@dada00321/Hy89EaT6We)
➡️ API_test_260428

### 📌 Step-0(b). Review 原本的 JWT 設定 (JSON)
專案 (API_test_260428) > appsetting.json 裡面原本 "JWT 設定" 寫法如下
```
"JwtSettings": {
  "SecretKey": "48d67a0b-3fc7-4dc2-b641-2c625a4c7ed4", // 密鑰 | 至少 32 位數 (此處 36 位數)
  "Issuer": "dada00321", // 發行者
  "Audience": "dada00321" // 受眾
},
```

### 📌 Step-1. 建立設定 class: JwtSetting.cs
專案按右鍵 → 新增資料夾 Settings 

右鍵: Settings → 新增類別 JwtSettings.cs：
```
namespace API_test_260428.Settings
{
    public class JwtSettings
    {
        public string SecretKey { get; set; } = "";
        public string Issuer { get; set; } = "";
        public string Audience { get; set; } = "";
    }
}
```

### 📌 Step-2. Program.cs 登記
在 builder.Services.AddControllers(); 上面加：
```
// 將 appsettings.json 的 "JwtSettings" 綁定到 JwtSettings class
builder.Services.Configure<JwtSettings>(
    builder.Configuration.GetSection("JwtSettings")
);
```

---

接著，修改 Program.cs 裡原本讀 JWT 設定的寫法：
將原本的寫法（用 "魔法字串" 讀取 JSON）
```
var _jwtSetting = builder.Configuration.GetSection("jwtSettings");
var _securityKey = _jwtSetting["SecretKey"] ?? "";
var _issuer = _jwtSetting["Issuer"];
var _audience = _jwtSetting["Audience"];
var _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_securityKey));
```

改寫成以下寫法（用 "強型別" 讀取 Class）
```
var jwtSettings = builder.Configuration
                  .GetSection("JwtSettings")
                  .Get<JwtSettings>()!;
var _key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey));
var _issuer = jwtSettings.Issuer;
var _audience = jwtSettings.Audience;
```

### 📌 Step-3. AuthService 改成注入 JwtSettings
修改 Services/AuthService.cs

註解掉將原本的寫法
```
// private readonly IConfiguration _config;

/*
var secretKey = _config["JwtSettings:SecretKey"] ?? "";
var issuer = _config["JwtSettings:Issuer"];
var audience = _config["JwtSettings:Audience"];
*/

/*
var secretKey = _config["JwtSettings:SecretKey"] ?? "";
var issuer = _config["JwtSettings:Issuer"];
var audience = _config["JwtSettings:Audience"];
*/
```

改寫成以下寫法
```
using API_test_260428.Settings;
using Microsoft.Extensions.Options;

public class AuthService: IScopedService {
    // 建構子改成注入 JwtSettings
    private readonly JwtSettings _jwtSettings;

    public AuthService(DeviceMonitorDbContext context, IOptions<JwtSettings> jwtOptions)
    {
        _context = context;
        _jwtSettings = jwtOptions.Value;  // .Value 才是真正的 JwtSettings 物件
    }

    // 直接用屬性取值，有型別、有自動補字
    var secretKey = _jwtSettings.SecretKey;
    var issuer = _jwtSettings.Issuer;
    var audience = _jwtSettings.Audience;
}
```

### 📌 Step-4. 測試 => 完成
完成「.NET 強型別設定」改寫後，若無紅字，並透過 Swagger UI 測試都沒問題，就成功囉