Options validation in ASP.NET Core: ValidateDataAnnotations and its reflection cost, Validate delegates, IValidateOptions<T> for cross-property and service-dependent rules, ValidateOnStart to fail at host start-up, ValidateObjectMembers and ValidateEnumeratedItems for nested types, the compile-time [OptionsValidator] source generator for AOT, OptionsValidationException behaviour on reload, and testing validators.
Options validation runs as the last step when an options object is built. ValidateDataAnnotations() applies attributes such as [Required], [Range] and [Url]; Validate(o => ..., "message") adds small rules; IValidateOptions<T> handles cross-property rules, named options or rules that need services.
Without ValidateOnStart() validation is lazy: a missing key surfaces as a 500 on the first request that reads the options, possibly hours after the deployment looked healthy. With it, the host validates during start-up, the process exits with every failure listed, and the orchestrator keeps the old version serving.
Nested objects need [ValidateObjectMembers] and collections [ValidateEnumeratedItems]. For Native AOT, the [OptionsValidator] source generator writes the DataAnnotations checks at compile time with no reflection.
The trade-off: a few attributes and a class, in exchange for configuration errors becoming start-up errors with clear messages.
"Options validation is the last step of the options factory: after binding and post-configure, every registered
IValidateOptions<T>runs, and any failure throws anOptionsValidationExceptionthat lists all the problems. WithoutValidateOnStart, that happens lazily, the first time something reads.Value, which is usually the first request in production. WithValidateOnStart, the host builds and validates those options during start-up, so the process exits with a clear message and the deployment never becomes ready.I layer the rules. Attributes cover the simple things:
[Required]on the base URL,[Range]on retries. AValidatedelegate handles a one-line rule. Anything with logic, like 'the timeout must be shorter than the retry budget' or 'in production, the sandbox flag must be false', goes into anIValidateOptions<T>class, which can takeIHostEnvironmentthrough DI and is easy to unit test. Nested objects aren't validated by default, so I mark them[ValidateObjectMembers].For example, at [company] a release went out with a renamed configuration section; every property bound to its default and the service called the payment gateway's sandbox URL in production for [20 minutes] before anyone noticed. With
[Required]andValidateOnStart, the new pods would have crash-looped and the old version stayed live. For AOT services I use the[OptionsValidator]source generator, which generates the same checks without reflection. The mistake I see is validation withoutValidateOnStart: the rules exist, but they fire at the worst possible time."
| Tool | Use for | Notes |
|---|---|---|
ValidateDataAnnotations() |
[Required], [Range], [Url], [RegularExpression], [MinLength] |
Reflection; not trim-safe |
Validate(o => cond, "message") |
One-line rules | Several calls allowed |
IValidateOptions<T> |
Cross-property rules, named options, injected services | Register as singleton |
[OptionsValidator] partial class |
DataAnnotations at compile time | AOT-friendly, .NET 8+ |
ValidateOnStart() |
Fail during host start-up | Without it, validation is lazy |
[ValidateObjectMembers] / [ValidateEnumeratedItems] |
Nested objects and lists | Opt-in |
| Situation | Without ValidateOnStart |
With ValidateOnStart |
|---|---|---|
| Start-up | Nothing | Validated; host fails to start on error |
First .Value |
Validated; throws in the request | Already validated |
Reload via IOptionsMonitor |
Rebuilt and validated at next CurrentValue |
Same: throws at the read site |
After adding ValidateOnStart to every options class in a [12-service] platform, two latent misconfigurations in test environments showed up on the next deployment as pods that failed to start with readable messages (Payments:BaseUrl: The BaseUrl field is required.). Before, both had surfaced only as 500s on rarely used endpoints.
Checks whether the candidate understands the validation flow (bind, post-configure, validate, and when that runs) and uses it to keep bad configuration from ever serving traffic.
Green flags
ValidateOnStart and explains why lazy validation is dangerous for deployments and rollbacks.[Required], [Range]) from logic rules in IValidateOptions<T>, with an example of each.[ValidateObjectMembers].[OptionsValidator] generator for AOT and why: no reflection.Red flags
if statements in constructors.OptionsFactory<T>.Create(name)
new T()
β IConfigureOptions<T> (bind)
β IPostConfigureOptions<T>
β IValidateOptions<T>[] βββ DataAnnotations, Validate(...), your validators
β collect every failure
βΌ
any failed? ββyesβββΊ throw OptionsValidationException(name, type, failures)
All validators run, so one exception reports every problem rather than the first.
ValidateOnStart() registers the options type with the host's start-up validator. During StartAsync, before hosted services and the server start, the host resolves each registered options type (and name) and so runs validation. If any fail, start-up throws an AggregateException/OptionsValidationException and the process exits non-zero; Kubernetes or Container Apps keeps the old revision serving.
ValidateDataAnnotations uses Validator.TryValidateObject with validateAllProperties: true, which only checks the top-level object. Nested objects are skipped unless you use the Options attributes:
PaymentOptions
ββ BaseUrl [Required, Url] checked
ββ Retry RetryOptions NOT checked ββΊ add [ValidateObjectMembers]
ββ Webhooks List<WebhookOptions> NOT checked ββΊ add [ValidateEnumeratedItems]
The reflection it needs is not safe under trimming, which is why the generator exists.
[OptionsValidator]
public partial class PaymentOptionsValidator : IValidateOptions<PaymentOptions>;
The generator reads the DataAnnotations attributes on PaymentOptions at compile time and emits a Validate method with direct property checks. You register it as IValidateOptions<PaymentOptions> instead of calling ValidateDataAnnotations(). Unsupported attributes produce compile-time diagnostics.
With IOptionsMonitor, a change clears the cache and the next CurrentValue rebuilds and validates. If invalid, that read throws. Treat OptionsValidationException in logs as a configuration incident and validate changes before publishing them (for example, a pipeline step that runs the validators against the new App Configuration snapshot).
ValidateOnStart; compare when the error appears.[ValidateObjectMembers].ValidateDataAnnotations with an [OptionsValidator] class and inspect the generated code in your IDE (Dependencies β Analyzers).IValidateOptions<T> that uses IHostEnvironment, and unit test it with both environments.PublishAot=true and compare trimming warnings for the two approaches.Layered validation with attributes, nested objects, a cross-property validator that uses a service, and the source generator.
// PaymentOptions.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.Options;
namespace Shop.Payments;
public sealed class PaymentOptions
{
public const string Section = "Payments";
[Required, Url] public string BaseUrl { get; init; } = "";
[Required] public string ApiKey { get; init; } = "";
public bool UseSandbox { get; init; } = true;
[Range(typeof(TimeSpan), "00:00:01", "00:00:30")] public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
[ValidateObjectMembers] public RetryOptions Retry { get; init; } = new(); // nested: opt in
[ValidateEnumeratedItems] public List<WebhookOptions> Webhooks { get; init; } = [];
}
public sealed class RetryOptions
{
[Range(0, 5)] public int MaxAttempts { get; init; } = 3;
[Range(typeof(TimeSpan), "00:00:00", "00:01:00")] public TimeSpan Budget { get; init; } = TimeSpan.FromSeconds(30);
}
public sealed class WebhookOptions { [Required, Url] public string Url { get; init; } = ""; }
// Compile-time DataAnnotations checks: no reflection, safe for trimming and Native AOT
[OptionsValidator]
public sealed partial class PaymentOptionsAttributeValidator : IValidateOptions<PaymentOptions>;
// Rules that need logic or services
public sealed class PaymentOptionsRulesValidator(IHostEnvironment env) : IValidateOptions<PaymentOptions>
{
public ValidateOptionsResult Validate(string? name, PaymentOptions o)
{
var failures = new List<string>();
if (o.Timeout * o.Retry.MaxAttempts > o.Retry.Budget)
failures.Add($"Timeout x MaxAttempts ({o.Timeout * o.Retry.MaxAttempts}) exceeds Retry:Budget ({o.Retry.Budget}).");
if (env.IsProduction() && o.UseSandbox)
failures.Add("UseSandbox must be false in Production.");
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
}
}
// Program.cs
using Microsoft.Extensions.Options;
using Shop.Payments;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions<PaymentOptions>()
.BindConfiguration(PaymentOptions.Section)
.ValidateOnStart(); // run every validator below during host start-up
builder.Services.AddSingleton<IValidateOptions<PaymentOptions>, PaymentOptionsAttributeValidator>();
builder.Services.AddSingleton<IValidateOptions<PaymentOptions>, PaymentOptionsRulesValidator>();
var app = builder.Build();
app.Run(); // with bad config: OptionsValidationException lists every failure, process exits
// xUnit: validators are plain classes
[Fact]
public void Sandbox_is_rejected_in_production()
{
var env = new FakeHostEnvironment { EnvironmentName = Environments.Production };
var result = new PaymentOptionsRulesValidator(env).Validate(null, new PaymentOptions { UseSandbox = true });
Assert.True(result.Failed);
}
file sealed class FakeHostEnvironment : IHostEnvironment
{
public string EnvironmentName { get; set; } = Environments.Development;
public string ApplicationName { get; set; } = "Tests";
public string ContentRootPath { get; set; } = "";
public Microsoft.Extensions.FileProviders.IFileProvider ContentRootFileProvider { get; set; } = null!;
}
ValidateOnStart. Why it is wrong: Errors only appear on the first read, usually a production request. Instead: Always chain ValidateOnStart() for options the app cannot run without.ValidateOnStart so a bad configuration fails the readiness gate, and make the pipeline stop on a revision that does not become ready.[ValidateObjectMembers] and [ValidateEnumeratedItems].ValidateDataAnnotations in a Native AOT or trimmed app. Why it is wrong: It relies on reflection over attributes that trimming can remove. Instead: Use the [OptionsValidator] source generator.Validate lambdas in Program.cs. Why it is wrong: It is hard to read and impossible to unit test. Instead: Write one IValidateOptions<T> class per options type.ValidateOptionsResult.Fail(list).CurrentValue is read. Instead: Validate changes before publishing and alert on OptionsValidationException.Fail-fast configuration is cheap insurance. A pod that refuses to start with "Payments:ApiKey is required" is a non-event: the orchestrator keeps the old revision and the pipeline goes red. The same mistake without validation is an incident. I aim for every options class to be validated at start-up, with messages that name the key so whoever is on call can fix it without reading code. I keep validation about shape and safety (required, ranges, combinations, environment guards) and leave connectivity checks such as "can I reach the database" to health checks, so a downstream outage doesn't stop the app from starting.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
DataAnnotations + ValidateDataAnnotations |
Simple rules, JIT apps | Reflection | Native AOT |
[OptionsValidator] generator |
Same rules, AOT/trimmed apps | Build-time code | Rules that need services |
IValidateOptions<T> |
Cross-property, environment-aware rules | A class per type | One-line checks |
| Health checks | Reachability of dependencies | Runtime probe | Shape validation (do that at start-up) |
The Generic Host (IHost) is the common runtime shell for every modern .NET app, web or worker: it owns configuration, logging, dependency injection and the application lifetime. WebApplication.CreateBuilder(args) creates one with sensible defaults: appsettings.json, appsettings.{Environment}.json, user secrets in Development, environment variables and command-line args; console, debug and EventSource logging; and Kestrel. Build() freezes the service collection and builds the IServiceProvider. Run() starts hosted services, then the web server, and blocks until shutdown. On SIGTERM or Ctrl+C the host fires ApplicationStopping, stops accepting requests, lets in-flight ones finish, stops hosted services and exits within HostOptions.ShutdownTimeout (30 seconds by default). The trade-off: the defaults are great, but you must understand them to override them deliberately.
ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.
:, e.g. ConnectionStrings:Default.__ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.
How to tell it (STAR)
**S:** At [company], a release renamed our payment configuration section and production quietly started using the sandbox gateway; orders were confirmed but nobody was charged. **T:** I had to stop the loss, then make that class of mistake impossible to deploy. **A:** I rolled back, worked with finance to reconcile [20 minutes] of orders, and confirmed with the configuration debug view that no keys matched the new section, so everything had defaulted. I then removed unsafe defaults, added required-field validation and a rule that rejects sandbox mode in production, and turned on `ValidateOnStart` for every options class. **R:** On the next misconfiguration, a missing key in a test environment, the new revision failed to start with a clear message and the old one kept serving: [zero] customer impact.
Last updated 23 Nov 2026.