How to validate options on start in C#
Catch missing or invalid configuration the moment your application starts, instead of when a request finally hits the broken code path in production. Covers data annotations, ValidateOnStart, custom validation rules, and source-generated validators.
Configuration mistakes are some of the most frustrating bugs to track down. A missing connection string or an API key with a typo in its environment variable name often doesn't cause a problem at startup — the app boots happily, passes its health checks, and then fails hours later when the first request touches the code that needs that setting.
The options pattern in .NET lets you bind configuration sections to strongly typed classes, and it comes with built-in validation. Combined with ValidateOnStart, it lets your application fail fast: if the configuration is invalid, the app refuses to start and tells you exactly what's wrong.
Defining an options class
Start with a plain class that represents a section of your configuration, and decorate its properties with attributes from System.ComponentModel.DataAnnotations:
public class MyOptions
{
public const string SectionName = "MyOptions";
[Required]
public string Name { get; set; } = string.Empty;
[Range(0, 150)]
public int Age { get; set; }
[Required, Url]
public string ApiBaseUrl { get; set; } = string.Empty;
}[Required] also rejects empty strings by default, so initialising Name to string.Empty keeps the compiler's nullable warnings quiet without weakening the validation.
The matching section in appsettings.json:
{
"MyOptions": {
"Name": "My application",
"Age": 42,
"ApiBaseUrl": "https://api.example.com"
}
}Validating on start
Register the options with AddOptions<T>, bind them to the configuration section, and enable validation:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();BindConfigurationbinds theMyOptionssection of configuration (fromappsettings.json, environment variables, user secrets, etc.) to the class.ValidateDataAnnotationsvalidates the bound values against the attributes on the class.ValidateOnStartruns that validation as the host starts, rather than waiting until the options are first used.
If you're using a Startup class instead of the minimal hosting model, the same chain goes in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
}Consuming the options doesn't change at all — inject IOptions<MyOptions> wherever you need them:
public class MyService(IOptions<MyOptions> options)
{
private readonly MyOptions _options = options.Value;
}Why ValidateOnStart matters
ValidateOnStart was introduced in .NET 6. Without it, options are validated lazily — only the first time IOptions<MyOptions>.Value is accessed, which is typically when a class that depends on them is first resolved. An invalid configuration could therefore go unnoticed until that particular code path runs in production.
With ValidateOnStart, the host throws an OptionsValidationException before it starts accepting requests, with a message that points straight at the problem:
Microsoft.Extensions.Options.OptionsValidationException:
DataAnnotation validation failed for 'MyOptions' members: 'ApiBaseUrl' with the error: 'The ApiBaseUrl field is required.'In a containerised environment this is exactly what you want: the new deployment fails its rollout immediately, and the previous healthy version keeps serving traffic.
Custom validation rules
Data annotations cover the simple cases, but some rules involve more than one property, or are just easier to express in code. For those, chain a Validate call with a predicate and an error message:
builder.Services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateDataAnnotations()
.Validate(
options => options.ApiBaseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase),
"ApiBaseUrl must use HTTPS.")
.ValidateOnStart();For more involved logic — or when the validation needs other services — implement IValidateOptions<T>. It can report several failures at once, which is friendlier than fixing one error per restart:
public class MyOptionsValidator : IValidateOptions<MyOptions>
{
public ValidateOptionsResult Validate(string? name, MyOptions options)
{
var failures = new List<string>();
if (options.Name.Contains(' '))
{
failures.Add("Name must not contain spaces.");
}
if (!options.ApiBaseUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
failures.Add("ApiBaseUrl must use HTTPS.");
}
return failures.Count > 0
? ValidateOptionsResult.Fail(failures)
: ValidateOptionsResult.Success;
}
}Register it alongside the options, and it'll run as part of the same start-up validation:
builder.Services.AddSingleton<IValidateOptions<MyOptions>, MyOptionsValidator>();Validating nested options
ValidateDataAnnotations only validates the properties of the top-level class. If your options contain a nested object, its attributes are ignored unless you opt in. Since .NET 8 you can do that with [ValidateObjectMembers] (and [ValidateEnumeratedItems] for collections) — used together with the source-generated validator described below:
public class MyOptions
{
[Required]
public string Name { get; set; } = string.Empty;
[ValidateObjectMembers]
public RetryOptions Retry { get; set; } = new();
}
public class RetryOptions
{
[Range(1, 10)]
public int MaxAttempts { get; set; } = 3;
}Source-generated validators (.NET 8+)
ValidateDataAnnotations uses reflection, which isn't compatible with trimming or Native AOT. .NET 8 added a source generator that produces the validation code at compile time instead. Declare an empty partial class marked with [OptionsValidator]:
[OptionsValidator]
public partial class MyOptionsValidator : IValidateOptions<MyOptions>
{
}Then register it in place of ValidateDataAnnotations:
builder.Services.AddOptions<MyOptions>()
.BindConfiguration(MyOptions.SectionName)
.ValidateOnStart();
builder.Services.AddSingleton<IValidateOptions<MyOptions>, MyOptionsValidator>();The generator reads the same data annotation attributes, so you don't need to change the options class — you just get faster, reflection-free validation that also supports nested members.
Summary
- Bind configuration to strongly typed classes with
AddOptions<T>().BindConfiguration(...). - Describe the rules with data annotations,
Validate(...)orIValidateOptions<T>. - Always add
ValidateOnStart(), so a bad configuration stops the app at startup instead of failing at runtime.