ASP.NET Core › Configuration & Options Pattern

How do you validate configuration options at application startup to fail fast on misconfiguration, using ValidateDataAnnotations and ValidateOnStart?

Advanced

Answer

Chaining .ValidateDataAnnotations().ValidateOnStart() on the options builder ensures configuration is validated immediately when the application starts (rather than lazily on first use), causing the application to fail to launch with a clear error message for missing or invalid required settings, instead of a confusing failure discovered only when a specific code path first accesses the misconfigured option deep into runtime.
public class SmtpSettings {
    [Required] public string Host { get; set; } = "";
    [Range(1, 65535)] public int Port { get; set; }
}

builder.Services.AddOptions<SmtpSettings>()
    .Bind(builder.Configuration.GetSection("Smtp"))
    .ValidateDataAnnotations()
    .ValidateOnStart();
Real-world example A misconfigured production deployment missing the required Smtp:Host setting now fails immediately at startup with a clear validation error, instead of running until the first email-send attempt fails hours later with a confusing null reference exception.

Common follow-ups: How do you write custom validation logic beyond DataAnnotations using IValidateOptions?;What happens without ValidateOnStart -- when does validation actually run?