📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š Interview question

Show me how you validate options in ASP.NET Core so the app fails fast on bad configuration. Cover DataAnnotations with ValidateDataAnnotations, ValidateOnStart, custom rules with Validate and IValidateOptions<T>, nested objects, and the source-generated [OptionsValidator].

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.

Mid-Level Coding Intermediate aspnet-core configuration data-annotations fail-fast options-validation source-generators

🎯 Key points

  • Without validation, missing or wrong config surfaces on the first request that uses it, often in production
  • ValidateDataAnnotations runs [Required], [Range], [Url] etc. when the options are built; it uses reflection
  • ValidateOnStart makes the host build and validate the options during start-up, so a bad deployment never becomes ready
  • Validate(o => ..., "message") for small rules; IValidateOptions<T> for cross-property rules, named options or injected services
  • Nested classes and collections are not validated unless marked [ValidateObjectMembers] / [ValidateEnumeratedItems]
  • [OptionsValidator] on a partial class implementing IValidateOptions<T> generates validation code at compile time: trim and AOT safe
  • Failures throw OptionsValidationException listing every failure; on reload the exception surfaces where CurrentValue is read
  • Validators are plain classes: unit test them directly

⏱ 30-second answer

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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"Options validation is the last step of the options factory: after binding and post-configure, every registered IValidateOptions<T> runs, and any failure throws an OptionsValidationException that lists all the problems. Without ValidateOnStart, that happens lazily, the first time something reads .Value, which is usually the first request in production. With ValidateOnStart, 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. A Validate delegate 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 an IValidateOptions<T> class, which can take IHostEnvironment through 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] and ValidateOnStart, 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 without ValidateOnStart: the rules exist, but they fire at the worst possible time."


The tools

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

When does validation run?

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

Production example

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.

πŸ” What the interviewer is checking

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

  • Uses ValidateOnStart and explains why lazy validation is dangerous for deployments and rollbacks.
  • Distinguishes attribute rules ([Required], [Range]) from logic rules in IValidateOptions<T>, with an example of each.
  • Knows nested objects need [ValidateObjectMembers].
  • Mentions the [OptionsValidator] generator for AOT and why: no reflection.

Red flags

  • Validates configuration by hand with if statements in constructors.
  • Doesn't know when validation runs.
  • Puts connectivity checks in start-up validation so a database blip blocks deployments.

πŸ“š Learn in depth

1. Where validation sits

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.

2. ValidateOnStart

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.

3. DataAnnotations and its limits

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.

4. The [OptionsValidator] source generator

[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.

5. Reload and validation

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).

Try it yourself

  1. Remove a required key and start the app with and without ValidateOnStart; compare when the error appears.
  2. Add a nested class with an invalid value and see that it passes until you add [ValidateObjectMembers].
  3. Replace ValidateDataAnnotations with an [OptionsValidator] class and inspect the generated code in your IDE (Dependencies β†’ Analyzers).
  4. Write an IValidateOptions<T> that uses IHostEnvironment, and unit test it with both environments.
  5. Publish with PublishAot=true and compare trimming warnings for the two approaches.

πŸ’» Code

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!;
}

⚠ Common mistakes

  • Mistake: Adding validation without 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.
  • Mistake: Treating a green deployment as proof the configuration is right when validation is lazy. Why it is wrong: The pipeline's smoke test and readiness probe pass because they never touch the misconfigured feature, so the release is promoted, the old revision is retired, and rollback becomes an incident rather than automatic. Instead: Use ValidateOnStart so a bad configuration fails the readiness gate, and make the pipeline stop on a revision that does not become ready.
  • Mistake: Expecting nested objects and lists to be validated. Why it is wrong: DataAnnotations only checks top-level properties. Instead: Mark them [ValidateObjectMembers] and [ValidateEnumeratedItems].
  • Mistake: Using 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.
  • Mistake: Putting cross-property logic in many 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.
  • Mistake: Returning on the first failure. Why it is wrong: Operators fix one problem, redeploy, and hit the next. Instead: Collect all failures and return ValidateOptionsResult.Fail(list).
  • Mistake: Including secret values in failure messages. Why it is wrong: The message is logged and may reach log analytics. Instead: Name the key and the rule, never the value of a secret.
  • Mistake: Assuming start-up validation protects reloads. Why it is wrong: A later invalid change throws where CurrentValue is read. Instead: Validate changes before publishing and alert on OptionsValidationException.

πŸ› Senior insight: trade-offs

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)

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions the host failing to start. Why: Checks they understand host start-up order and what happens when start-up throws.
    How to answer

    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.

  2. When: Candidate mentions a section name mismatch binding nothing. Why: Checks they can trace which provider supplied (or failed to supply) a key.
    How to answer

    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.

    • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
    • Environment variables use __ 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.

πŸ›  Real-world problems: how you handle them

Renamed config section silently sent production payments to the sandbox
Situation
A checkout service at [company] processing about [$40k] an hour. A refactor renamed the `PaymentGateway` section to `Payments` in code, but the Container Apps environment variables still used the old prefix.
Signals
Payment success rate stayed at 100% but no settlements arrived; the gateway dashboard showed live traffic hitting the sandbox; customers reported orders confirmed without charges.
Investigation
Compared `GetDebugView()` output from a staging instance with the options class: no `Payments:*` keys existed, so every property bound to its default, including `UseSandbox = true` and the sandbox base URL. Git history showed the section rename in the release.
Resolution
Immediate: rolled back to the previous revision, then reconciled the [20 minutes] of unpaid orders with the finance team. Fix: renamed the environment variables, added `[Required]` to `BaseUrl` and `ApiKey`, removed the sandbox URL as a default, and added an `IValidateOptions<T>` rejecting `UseSandbox` in Production, all with `ValidateOnStart`.
Prevention
Every options class now uses `ValidateOnStart`; a unit test runs each validator against the production configuration shape; infrastructure-as-code and options section names are checked in the same pull request.

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.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me