skip to content

In ASP.NET Core, how do ValidateDataAnnotations and ValidateOnStart make a missing payment-gateway API key fail at startup instead of on the first request?

level: middleimportance: should knowfreq 55%

answer

  1. attributes on the options class
  2. OptionsValidationException with Failures
  3. lazy by default: first Value read
  4. ValidateOnStart: checked when the host starts
  5. nested classes need [ValidateObjectMembers]

basics

~20 s

ValidateDataAnnotations runs the [Required], [Range] and similar attributes when the options object is built, throwing OptionsValidationException; ValidateOnStart forces that build while the host starts, so the app refuses to start instead of failing on the first request.

solid answer

~40 s

Put DataAnnotations attributes on the options class (`[Required] public string ApiKey`, `[Range(1, 120)] public int TimeoutSeconds`) and chain `.ValidateDataAnnotations()` after `BindConfiguration("PaymentGateway")`. Validation runs inside the options factory, after binding and post-configure, so by default it fires on the first `.Value` read, which in a web app is often the first checkout request. Chaining `.ValidateOnStart()` registers a startup validator that the host runs in `StartAsync` before hosted services, including the web server, start; a failure throws `OptionsValidationException`, whose `Failures` lists each message, and the process exits. `Validate(o => ..., "message")` adds a lambda rule on the same chain, and `AddOptionsWithValidateOnStart<T>()` is the shorthand. Attributes are not applied to nested objects unless the property carries `[ValidateObjectMembers]`.

code

json · 6 lines
json
{
  "PaymentGateway": {
    "BaseUrl": "https://gateway.example/v2",
    "TimeoutSeconds": 300
  }
}

go deeper

for a junior

Know that attributes like [Required] on an options class can be checked with ValidateDataAnnotations.

for a middle

Explain that validation runs when the options are first built and that ValidateOnStart moves it to host startup, throwing OptionsValidationException.

for a senior

Validate every critical settings class at startup, cover nested classes with [ValidateObjectMembers], and make the failure readable in deployment logs.

for a principal

Make startup validation a rule for every settings class so misconfiguration fails a deployment rather than a customer request.

## The problem The subscription-box service charges customers through a payment gateway. If `PaymentGateway:ApiKey` is missing in production, the options object binds with an empty key and nobody notices until the first customer's checkout fails. Options validation moves that discovery to deployment. ## Declaring the rules ```csharp public sealed class PaymentGatewayOptions { [Required, Url] public string BaseUrl { get; set; } = ""; [Required] public string ApiKey { get; set; } = ""; [Range(1, 120)] public int TimeoutSeconds { get; set; } = 30; } builder.Services.AddOptions<PaymentGatewayOptions>() .BindConfiguration("PaymentGateway") .ValidateDataAnnotations() .Validate(o => !o.BaseUrl.StartsWith("http:"), "BaseUrl must use https.") .ValidateOnStart(); ``` - `ValidateDataAnnotations()` registers a validator that runs `Validator.TryValidateObject` with all properties; the method ships in `Microsoft.Extensions.Options.DataAnnotations`, which web projects get through the shared framework. - `Validate(predicate, failureMessage)` adds a rule the attributes cannot express; without a message the failure reads "A validation error has occurred.". - `[Required]` on a string rejects `null` and empty strings, so the empty initializer above fails when no key is configured. ## When validation runs The options factory builds an instance in a fixed order: create, run configure actions (the binding), run post-configure actions, then run every `IValidateOptions<T>`. Any failure throws `OptionsValidationException`. The question is **when the factory runs**: | Setup | First validation | |---|---| | No `ValidateOnStart` | First read of `.Value`, `CurrentValue` or `Get(name)`, typically inside a request | | `.ValidateOnStart()` | During `app.Run()` / `StartAsync`, before hosted services and the server start | | `IOptionsMonitor<T>` after a reload | On the rebuild after each change | `ValidateOnStart()` adds an `IStartupValidator` entry that resolves the options by name. The host calls the startup validator before starting any hosted service, so Kestrel never begins listening and the deployment's health check fails fast. The same early read also surfaces binding errors such as an unconvertible number. ## Reading the failure `OptionsValidationException` exposes `OptionsName`, `OptionsType` and `Failures`; its `Message` joins the failures with `; `. A DataAnnotations failure reads like `DataAnnotation validation failed for 'PaymentGatewayOptions' members: 'ApiKey' with the error: 'The ApiKey field is required.'.` Log it at startup and the cause is obvious from the deployment output. ## Nested objects and collections DataAnnotations validation looks at the options object's own properties. A nested settings class is **not** validated unless you opt in: - `[ValidateObjectMembers]` on a property validates the nested object's attributes. - `[ValidateEnumeratedItems]` on a collection property validates each element. Without them, `[Required]` inside `PaymentGatewayOptions.Webhook` is silently ignored. ## Pitfalls that pass validation | Declaration | Why it never fails | |---|---| | `[Required] public int TimeoutSeconds { get; set; }` | An `int` is never null; a missing key leaves `0`, which `[Required]` accepts. Use `[Range(1, 120)]` or `int?` | | `[Required] public string ApiKey { get; set; } = "placeholder";` | The initializer satisfies the rule when the key is missing | | Rules on a nested class without `[ValidateObjectMembers]` | The nested object is never visited | Each of these looks protected in code review and lets a missing setting through. ## Shortcuts and limits 1. `builder.Services.AddOptionsWithValidateOnStart<PaymentGatewayOptions>()` returns an `OptionsBuilder` with `ValidateOnStart()` already applied. 2. Validation never runs for options nobody registered a validator for; binding alone validates nothing. 3. Reflection-based DataAnnotations validation is not trimming-friendly; the compile-time `[OptionsValidator]` generator is the alternative for trimmed or Native AOT apps. ## Interview checklist - Attributes plus `ValidateDataAnnotations()`, lambdas with `Validate`. - Validation is lazy until `ValidateOnStart()`. - `OptionsValidationException.Failures` carries the messages. - Nested classes need `[ValidateObjectMembers]`.

  • Without ValidateOnStart, when would the missing ApiKey be reported?
    On the first read of the options, for example when a checkout request resolves a service that reads `IOptions<PaymentGatewayOptions>.Value`. The factory binds, then validates, then throws `OptionsValidationException` inside that request, so the first customer sees the failure instead of the deployment.
  • Why is a [Required] attribute on a property of a nested Webhook settings class ignored?
    `ValidateDataAnnotations` validates the options object's own properties and recurses only into properties marked `[ValidateObjectMembers]` (or `[ValidateEnumeratedItems]` for collections). Add that attribute to the `Webhook` property so the nested rules run.

  • ValidateDataAnnotations validates the options as soon as the app is built, so ValidateOnStart is redundant.
  • Binding a section automatically enforces [Required] attributes on the options class.
  • ValidateOnStart validates options on every request instead of once.
  • DataAnnotations validation recurses into every nested settings object by default.
  • A failed options validation logs a warning and lets the app continue with defaults.