ASP.NET Core Interview Question #32

How do you validate strongly typed configuration options?

Application Structure & Configuration Junior Beginner

Quick Interview Answer

ASP.NET Core can validate options when they are configured. Validation prevents the application from running with missing or invalid settings.

Detailed Explanation

ASP.NET Core can validate options when they are configured. Validation prevents the application from running with missing or invalid settings.

Data annotation attributes can be applied to an options class and enabled with ValidateDataAnnotations(). Custom validation rules can be added with Validate(). ValidateOnStart() forces validation during startup rather than waiting until the options are first requested.

Startup validation is valuable for required production settings because configuration errors are detected immediately.

Code Example

public class ApiSettings
{
    [Required]
    public string BaseUrl { get; set; } = string.Empty;

    [Range(1, 300)]
    public int TimeoutSeconds { get; set; }
}

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