Configuration & appsettings.json

লেসন ২১ / ৫০

Configuration Sources

ASP.NET Core layered config — পরবর্তীটি আগেরটিকে override করে:

  1. appsettings.json
  2. appsettings.{Environment}.json
  3. User Secrets (Dev only)
  4. Environment Variables
  5. Command-line args

appsettings.json

{
  "ConnectionStrings": {
    "Default": "Server=...;Database=MyDb;"
  },
  "Jwt": {
    "Key": "secret-key",
    "Issuer": "MyApi",
    "ExpiryMinutes": 60
  },
  "EmailSettings": {
    "SmtpHost": "smtp.gmail.com",
    "Port": 587
  }
}

Read in Code — IConfiguration

public class Foo {
    private readonly IConfiguration _cfg;
    public Foo(IConfiguration cfg) => _cfg = cfg;

    public void Use() {
        string conn = _cfg.GetConnectionString("Default");
        string key = _cfg["Jwt:Key"];
        int exp = _cfg.GetValue<int>("Jwt:ExpiryMinutes");
        var section = _cfg.GetSection("EmailSettings");
        string host = section["SmtpHost"];
    }
}

Options Pattern ⭐ (Best Practice)

// 1. POCO class
public class JwtOptions {
    public string Key { get; set; }
    public string Issuer { get; set; }
    public int ExpiryMinutes { get; set; }
}

// 2. Bind in Program.cs
builder.Services.Configure<JwtOptions>(builder.Configuration.GetSection("Jwt"));

// 3. Inject IOptions<T>
public class TokenService {
    private readonly JwtOptions _opt;
    public TokenService(IOptions<JwtOptions> opt) => _opt = opt.Value;

    public string Generate() {
        return $"Token signed with {_opt.Key}, expires in {_opt.ExpiryMinutes}m";
    }
}

IOptions vs IOptionsSnapshot vs IOptionsMonitor

  • IOptions<T> — Singleton, app start-এ একবার read
  • IOptionsSnapshot<T> — Scoped, প্রতি request-এ refresh
  • IOptionsMonitor<T> — Singleton, real-time change notification

User Secrets (Development) ⭐

# Init
dotnet user-secrets init --project MyApi

# Set
dotnet user-secrets set "Jwt:Key" "very-long-secret-key"
dotnet user-secrets set "ConnectionStrings:Default" "Server=...;Pwd=..."

# List
dotnet user-secrets list

# Stored in: %APPDATA%\Microsoft\UserSecrets\<id>\secrets.json

Environment Variables (Production)

# Linux/Docker
export Jwt__Key="prod-secret"             # __ = nesting

# docker-compose.yml
environment:
  - ConnectionStrings__Default=Server=...
  - Jwt__Key=prod-secret

Validation

public class JwtOptions {
    [Required, MinLength(32)] public string Key { get; set; }
    [Required] public string Issuer { get; set; }
    [Range(5, 1440)] public int ExpiryMinutes { get; set; }
}

builder.Services.AddOptions<JwtOptions>()
    .Bind(builder.Configuration.GetSection("Jwt"))
    .ValidateDataAnnotations()
    .ValidateOnStart();

⚠️ Security

  • Secret কখনোই appsettings.json-এ commit করবেন না
  • Production-এ environment variable / Azure Key Vault / AWS Secrets Manager