← Back to all articles

Proactive configuration validation in .NET: prevent errors before they happen

Published

When building robust .NET applications, one of the best practices is to validate your configuration at startup. This helps you avoid situations where critical parameters—like feature flags—are missing from appsettings.json (for example, after a merge conflict or accidental deletion).

If a value is missing, the app may still start and silently fall back to defaults (e.g., false for a bool). That’s how hidden, hard-to-trace production bugs are born. Instead, prefer a fail-fast approach: make the app refuse to start when configuration is invalid.

Problem example

{
  "FeatureManagement": {
    //"NewDashboard": true  // Missing parameter will default to false
  }
}

In this case, the app would start with NewDashboard = false even if you expected it to be true.

Step 1 — Define a configuration class

Create a class that represents your configuration section, for example FeaturesConfig.

public class FeaturesConfig
{
    public bool NewDashboard { get; set; }
}

This alone isn’t enough, because NewDashboard will default to false when the key is absent.

Step 2 — Add validation attributes

Use standard DataAnnotations to mark required fields. Make the property nullable so the binder can detect “missing” vs “false”.

using System.ComponentModel.DataAnnotations;

public class FeaturesConfig
{
    [Required]
    public bool? NewDashboard { get; set; }
}

Step 3 — Enable validation at startup

When registering options in Program.cs, add .ValidateDataAnnotations() and .ValidateOnStart().

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<FeaturesConfig>()
    .Bind(builder.Configuration.GetSection(nameof(FeaturesConfig)))
    .ValidateDataAnnotations()
    .ValidateOnStart();

var app = builder.Build();
app.Run();

Note: .ValidateOnStart() was introduced in .NET 6. With it, the app validates options during startup and throws an OptionsValidationException if required fields are missing.

This will immediately point to a configuration problem, protecting your system from unpredictable behavior in production.

image

This simple mechanism is an important step toward creating more stable and predictable applications.