Back to results for “Global Exception Handling & Middleware”
.NET › Configuration & Options

How do you validate configuration options at application startup to fail fast on misconfiguration?

Intermediate

Answer

Using ValidateDataAnnotations() combined with 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 if required settings are missing or invalid -- far preferable to a confusing NullReferenceException or incorrect behavior 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 'DataAnnotation validation failed' error, instead of silently 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?