Table of Contents

Catch Broken ASP.NET Core Configuration Before the First Request

Pattern classification: General learning material

Difficulty: Beginner to intermediate

Prerequisites: Comfortable reading basic C# and ASP.NET Core minimal API code, and registering services with builder.Services. Configuration providers, typed options, IValidateOptions<T>, ValidateOnStart, and integration tests with TestServer are introduced in the article. No AsiBackbone package or prior Learning material is required.

Sample scope: All the options APIs used here (BindConfiguration, IValidateOptions<T>, ValidateOnStart, IOptions<T>, and IOptionsMonitor<T>) are available in .NET 6 and later; the sample targets .NET 10. The default provider order described is the one WebApplication.CreateBuilder uses. Four behaviors were observed only in the tests and are labeled where they appear: the binder's exception message, the rejection of endpoints that end in a bare ? or #, what a reload does, and when IOptions<T> is first built. They were observed on .NET 10 and can change between versions. Authentication, authorization, the handling of the exported data, and the real outbound HTTP call are deliberately left out to isolate configuration and options validation; a production export endpoint needs access controls of its own. The orders API, the partner, every host name, and every key in the sample are fictional.

Verification: The application code, project files, and eleven in-process test methods in the appendix, two of them parameterized theories, which together run nineteen test cases, were compiled and run on .NET 10, and all nineteen cases passed on three consecutive runs; the appendix records the environment and command. Each behavior the article attributes to a named test is pinned by that test. Statements attributed to Microsoft's documentation reflect that documentation as of December 5, 2026, and were not otherwise tested. That includes the full default provider order (user secrets, command-line arguments, and the host-configuration fallback are not in the tests), the environment-variable naming rule beyond the one case tested, and what the documentation says about Secret Manager and environment variables as secret stores.

License: Original prose is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0), and original code examples are additionally offered under the MIT License, as described in the repository's licensing terms. Third-party material, where identified, remains under its original license.

What this article covers: a deployment that starts normally and fails on the first export request; how ASP.NET Core composes configuration from several providers, and how to find which one supplied the winning value without printing it; one optional integration bound to typed options with explicit enablement; validation that requires an endpoint only when the integration is enabled; ValidateOnStart, which moves that failure to host startup; the difference between a binding failure and a validation failure, and why only one of them can be kept from repeating the value; three endpoint cases side by side, plus the binding failure a disabled export still hits and a cosmetic setting that is allowed to default; what startup validation does not guarantee, including reloads and whether the partner is reachable; and diagnostics that name a setting without exposing its value.

In plain terms: think of a pilot's pre-flight checklist. The checklist does not prove the destination airport is open, and it does not cover what happens once the aircraft is airborne. It catches what can be known on the ground, such as a missing chart for a route the pilot intends to fly, before passengers board. A route the pilot will not fly today does not need a chart.

The Deployment Succeeded. The First Export Did Not.

Consider a hypothetical orders API. It has an optional integration: when enabled, POST /exports/orders sends the day's orders to a partner's HTTPS endpoint with an API key. Most environments leave it off. Production turns it on.

The team adds the integration the way many integrations are added: a settings class, a binding call, and an endpoint that reads the settings when it runs.

builder.Services.AddOptions<PartnerExportOptions>()
    .BindConfiguration("PartnerExport");
endpoints.MapPost("/exports/orders", async (
    IOptions<PartnerExportOptions> options,
    IPartnerExportSender sender,
    CancellationToken cancellationToken) =>
{
    var settings = options.Value;

    if (!settings.Enabled)
    {
        return Results.NotFound();
    }

    await sender.SendAsync(new Uri(settings.Endpoint!), settings.ApiKey!, /* ... */);
    return Results.Accepted();
});

The release goes out. PartnerExport:Enabled is true in production, and the API key arrives from the deployment platform. The endpoint value does not: it was added to the staging settings and never to production. The host starts. A general health check that does not exercise the optional export reports healthy. The dashboards are green. Hours later the scheduler calls POST /exports/orders, new Uri(null) throws ArgumentNullException, and the first to notice is the partner who did not receive a file.

The test WithoutValidationTheAppStartsAndTheFirstExportFails reproduces this: the host starts successfully, and the first export request fails with ArgumentNullException.

Nothing here is a framework defect. Binding does not require any property to have a value, and nothing reads the options until a request asks for them. Startup succeeded because startup never looked. Three questions follow, and the rest of the article answers them in order:

  1. Which configuration value actually reached the application?
  2. Which settings must be valid before the application serves traffic, and which may be absent?
  3. What does checking them at startup prove, and what does it not?

Which Value Won?

A reviewer who opens appsettings.json and appsettings.Production.json is reading two inputs, not the configuration. ASP.NET Core composes the configuration the application sees from several providers. Each provider reads one source and contributes keys. When two providers supply the same key, the one added later wins.

For an application created with WebApplication.CreateBuilder, Microsoft's configuration documentation lists the default application-configuration sources. Here they are in lowest-to-highest priority order, so each later source can override an earlier one:

  1. appsettings.json
  2. appsettings.{Environment}.json, for example appsettings.Production.json
  3. User secrets, only when the environment is Development
  4. Environment variables without the ASPNETCORE_ or DOTNET_ prefix
  5. Command-line arguments

The list is simplified. The documentation also describes a lower-priority fallback of host configuration, which is where variables with the DOTNET_ and ASPNETCORE_ prefixes end up, and notes that the command-line provider is added twice. The order applies to the default pipeline; an application that adds, removes, or reorders providers changes it.

Configuration keys are hierarchical, with : as the separator, so the export's endpoint is PartnerExport:Endpoint. Because : is not valid in environment variable names on every platform, the environment variable provider converts a double underscore to a colon: PartnerExport__Endpoint sets PartnerExport:Endpoint.

Here is one section traced through three layers:

Provider PartnerExport:Enabled PartnerExport:Endpoint PartnerExport:TimeoutSeconds
appsettings.json false https://partner.example.com/v1/orders 30
appsettings.Production.json true https://partner.example.com/v2/orders
Environment variables https://partner-eu.example.com/v2/orders
Composed result true, from the production file https://partner-eu.example.com/v2/orders, from the environment 30, from the base file

Nobody reviewing the two JSON files would predict the endpoint the application uses. The environment variable might be deliberate (the European partner endpoint for this region) or forgotten (left behind by an earlier migration). Either way, the composed configuration is what runs, and it is what deserves the review.

The test AHigherPrecedenceProviderOverridesTheCheckedInFiles builds exactly this stack. It writes the two JSON files to a temporary folder and sets two environment variables under a prefix unique to the test run, so variables already on the machine cannot affect the result. It asserts that the bound options carry the environment variable's endpoint and that the export uses it.

Find the provider without printing the value

When a value surprises you, the first instinct is to dump the configuration. Don't: a dump can expose connection strings, API keys, tokens, and other sensitive values supplied through configuration providers. IConfigurationRoot.GetDebugView() is useful on a developer's machine for exactly this reason, and dangerous in a shared log for the same reason.

The question "which provider supplied this key?" can be answered without the application code retaining, inspecting, or emitting the value. Providers are kept in the order they were added, and each can say whether it has a key:

public static string? WinningProvider(IConfigurationRoot configuration, string key)
{
    // Later providers win, so search from the last one added.
    foreach (var provider in configuration.Providers.Reverse())
    {
        if (provider.TryGet(key, out _))
        {
            return provider.ToString();
        }
    }

    return null;
}

TryGet does retrieve the value through its output parameter, but the discard (out _) means this helper never keeps or prints it. What comes back is the provider's description: for a JSON file it names the file by the path it was registered with, which can reveal directory layout in a shared log, and for the environment variable provider it names the prefix, if there is one. Treat that description as diagnostic text for an operator, not as a stable identifier to parse or to use in application logic. This sample relies on the descriptions of the built-in JSON and environment variable providers. If a custom or third-party provider's ToString() output has not been reviewed, log a label you chose deliberately instead or, where that is acceptable in your environment, provider.GetType().Name. The same test asserts that the endpoint and the API key came from the environment variable provider, that Enabled came from appsettings.Production.json, that TimeoutSeconds came from appsettings.json, and that none of those descriptions contains the API key or the overriding endpoint. Those assertions on description text verify the test; they are not a pattern for application code.

The helper reports which provider holds a key, and that provider wins even if the value it holds is an empty string. It returns nothing for a key that no provider has, and it cannot tell you why a value is present; that answer lives in your deployment process.

Bind One Optional Integration to Typed Options

The export's settings live in one class. Typed options, also called the options pattern, bind a configuration section to strongly typed options instances, so the rest of the application reads properties instead of string keys:

public sealed class PartnerExportOptions
{
    public const string SectionName = "PartnerExport";

    public bool Enabled { get; set; }

    public string? Endpoint { get; set; }

    public string? ApiKey { get; set; }

    public int TimeoutSeconds { get; set; } = 30;

    // Cosmetic: written into the export header. A default is harmless.
    public string SourceLabel { get; set; } = "orders-api";
}

Four decisions are visible in this class.

Enablement is explicit. Enabled defaults to false. The feature is not switched on by the presence of an endpoint, and it is not switched on because someone forgot to switch it off. An environment that wants the export says so.

Required is conditional. Endpoint and ApiKey are nullable because they are legitimately absent when the export is disabled. They are required only when Enabled is true. Marking them [Required] with data annotations would fail every environment that does not use the export.

Some values may default. TimeoutSeconds has a sensible default, and SourceLabel is cosmetic in this sample: it appears in the export file's header, and the default does not change where the export goes or whether it is delivered. Neither needs to stop the application. Failing startup for every optional setting trains people to paste placeholder values to make the error go away, which is worse than the missing value.

The endpoint is a string, not a Uri. That choice is about diagnostics; Binding failures are not validation failures explains it.

Validate the Rules, Not Just the Presence

The rules for this integration depend on each other, which is why they live in one validator class. An IValidateOptions<T> implementation receives the bound options and returns success or a list of failures:

public sealed class PartnerExportOptionsValidator : IValidateOptions<PartnerExportOptions>
{
    public ValidateOptionsResult Validate(string? name, PartnerExportOptions options)
    {
        if (!options.Enabled)
        {
            return ValidateOptionsResult.Success;
        }

        var failures = new List<string>();

        if (string.IsNullOrWhiteSpace(options.Endpoint))
        {
            failures.Add("PartnerExport:Endpoint is required when PartnerExport:Enabled is true.");
        }
        else if (!IsAdmissibleEndpoint(options.Endpoint))
        {
            failures.Add(
                "PartnerExport:Endpoint must be an absolute HTTPS URI with a host and no user information, query, or fragment.");
        }

        // ApiKey is required, and TimeoutSeconds must be between 1 and 120 ...

        return failures.Count == 0
            ? ValidateOptionsResult.Success
            : ValidateOptionsResult.Fail(failures);
    }
}

The complete class is in the appendix. Several properties of it matter more than its length.

A disabled feature skips the feature's rules, not binding. When Enabled is false, the validator returns success without checking the endpoint, the API key, or the timeout range, even if an old endpoint value is still present in some provider. That is the conditional rule doing its job; whether to clean up stale values is a separate housekeeping decision. Binding still runs before the validator, though, so a value that cannot be converted to its property's type stops startup even when the export is off; see Binding failures are not validation failures.

The rules are the same for every options name. The validator ignores its name parameter, so a named options instance of this type would get the same rules; the sample uses only the default name.

Every unmet requirement is reported together. An operator who fixes the endpoint and redeploys, only to learn about the missing API key on the next attempt, loses a whole deployment cycle. The test EveryUnmetRequirementIsReportedTogether enables the export with no endpoint, no API key, and a zero timeout, and asserts three failures, one for each setting.

Messages name the setting and the rule, never the value. "PartnerExport:Endpoint must be an absolute HTTPS URI" tells an operator exactly which key to fix. Echoing the value would be more convenient, and it would be a mistake: an endpoint URL can contain credentials in its user-information part (https://user:password@host) or a token in its query string, intentionally or by accident, and in this startup-failure path the host logs the exception that carries the message.

The admissibility rule itself is deliberately narrow:

// Shape only: says nothing about whether the host exists, answers, or can be trusted.
private static bool IsAdmissibleEndpoint(string value) =>
    Uri.TryCreate(value, UriKind.Absolute, out var uri)
    && uri.Scheme == Uri.UriSchemeHttps
    && uri.Host.Length > 0
    && uri.UserInfo.Length == 0
    && uri.Query.Length == 0
    && uri.Fragment.Length == 0;

It rejects a relative path and plain HTTP because they break this integration's endpoint requirements. It rejects user information, a query string, and a fragment as policy: they can carry credentials, tokens, or request-specific data that does not belong in a configured base endpoint. With this predicate on .NET 10, endpoints that end in a bare ? or # are rejected too; the theory below pins both cases. It does not resolve the host name, open a connection, or check a certificate; see What a valid shape does not prove.

Move the Failure to Startup with ValidateOnStart

The registration adds the validator and one more call:

public static IServiceCollection AddPartnerExport(this IServiceCollection services)
{
    services.AddOptions<PartnerExportOptions>()
        .BindConfiguration(PartnerExportOptions.SectionName)
        .ValidateOnStart();

    services.TryAddEnumerable(
        ServiceDescriptor.Singleton<IValidateOptions<PartnerExportOptions>, PartnerExportOptionsValidator>());

    return services;
}

Without ValidateOnStart(), validation runs the first time an options instance is created, as the options documentation explains. In the opening example, that would have been the first export request. With it, the options are created and validated while the host starts. An invalid configuration then makes app.StartAsync() (or app.Run()) throw an OptionsValidationException, and the host logs the failure. In the tested application, startup fails before the server can accept a request.

The theory AnEnabledExportWithAPolicyRejectedEndpointFailsBeforeServingARequest runs eight endpoints that this policy rejects through this registration with the export enabled: a missing endpoint, a relative path, plain HTTP, an HTTPS URL with credentials in its user information, one with a token in its query string, one with a secret in its fragment, and two that end in a bare ? or #. For each one it asserts that:

  • starting the host throws OptionsValidationException with exactly one failure, and that failure names PartnerExport:Endpoint;
  • neither the exception nor anything in the captured logs, including the host's own "Hosting failed to start" error event, contains the synthetic API key, the synthetic secret planted in the URL, or the endpoint value itself;
  • a request sent afterwards does not reach the application: the request-counting middleware saw no requests, and the export sender was never called.

That establishes absence from the exception and from the logging pipeline the test configures. It does not establish absence from every host-level diagnostic, telemetry, debugger, or crash-reporting channel.

The test shows that StartAsync() throws; it does not run a separate process. In a typical deployment, an unhandled startup failure fails the startup operation and commonly ends the process with a nonzero exit code. How the deployment platform reports that, and whether the previous version keeps running, depends on its configuration. That is where this failure belongs: in front of the person deploying, not in front of the partner.

Binding failures are not validation failures

Two different things can go wrong when options are created, and they fail differently.

A binding failure happens when a configuration value cannot be converted to the property's type. Configuration values are strings, and binding "thirty" to an int cannot succeed. On .NET 10, the version tested, the binder throws InvalidOperationException. Because binding happens when the options are created, ValidateOnStart surfaces binding failures at startup too, and it does so whether or not the feature is enabled: the test ADisabledExportStillHasToBind sets Enabled to false and the timeout to thirty, and startup still fails with the same kind of exception.

A validation failure happens after binding has succeeded: every value converted, but the combination breaks a rule. The validator reports it, and the host receives an OptionsValidationException.

The test AValueThatCannotBeConvertedIsABindingFailureNotAValidationFailure sets PartnerExport:TimeoutSeconds to thirty. It asserts that startup throws an InvalidOperationException that is not an OptionsValidationException, that its message names PartnerExport:TimeoutSeconds and System.Int32, and that no request reached the application. It also pins something worth knowing: on .NET 10, the binder's message repeats the raw value ('thirty'), and the host's startup-failure log repeats the exception.

In this test, the rejected timeout is harmless. But any key can receive a secret by mistake, and for a setting that normally carries one, the risk is real.

Suppose a credential-bearing value is bound to a type whose conversion can fail, such as an endpoint bound to Uri. A malformed value containing a token could then be quoted in an exception message and in the startup log. That is why Endpoint is a string in this sample. A string property avoids the URI type-conversion failure, so once binding succeeds, endpoint-shape problems in this sample go through the validator, whose messages you control. For settings whose malformed form could contain sensitive material, bind the raw value as a string and validate its shape yourself. That narrows one disclosure path; it does not guarantee that nothing else in binding, such as another property or a malformed settings file, can fail with a message of its own.

A third class of mistake fails neither way: a misspelled key binds nothing and raises nothing. For PartnerExport:Endpiont, the conditional rule catches the consequence, because the endpoint is missing while the export is enabled, but only if no other provider supplies a correctly spelled Endpoint. If a lower-priority file supplies a valid endpoint, the application can start with that older value, which is one more reason to review the composed configuration. That is luck, not a general guarantee: a misspelled Enabled leaves the export silently off, a misspelled TimeoutSeconds silently keeps the 30-second default, and a misspelled SourceLabel silently keeps orders-api. The binder can be asked to reject configuration keys that match no property by setting BinderOptions.ErrorOnUnknownConfiguration for a particular bind, for example BindConfiguration(section, binder => binder.ErrorOnUnknownConfiguration = true); this sample does not use or test that option.

Three Cases Side by Side

Configuration Startup First POST /exports/orders Test
Export disabled, with no endpoint or a leftover rejected one Succeeds 404; nothing is sent ADisabledExportStartsWithoutAnAdmissibleEndpoint (two cases)
Export enabled, with a valid HTTPS endpoint and an API key Succeeds 202; the sender receives the configured endpoint AnEnabledExportWithAValidEndpointStartsAndUsesIt
Export enabled, with the endpoint missing or rejected by the policy Fails with OptionsValidationException naming PartnerExport:Endpoint Never served AnEnabledExportWithAPolicyRejectedEndpointFailsBeforeServingARequest (eight cases)

The first row covers the endpoint rules only. A disabled export still fails startup when any value cannot be converted to its property's type, as ADisabledExportStillHasToBind shows.

One more case deliberately stays out of the failure column: the export enabled with a valid endpoint and without PartnerExport:SourceLabel configured. The test AMissingCosmeticSettingUsesItsDefault asserts that the application starts and the export uses the default label orders-api. A missing label does not change what the export does or whom it reaches, so a default is the right answer. Whether a setting deserves a startup failure depends on whether running without it would do the wrong thing, not on whether it appears in the settings file.

None of these tests calls the partner. The sender is a recording fake; the tests check which endpoint would be used, not whether anything answers there.

What Startup Validation Does Not Guarantee

ValidateOnStart makes a narrow promise: the options, as composed when the host started, satisfied the rules. Three things are outside that promise.

What a valid shape does not prove

An endpoint that passes the validator is an absolute HTTPS URI without embedded credentials. It might still name a host that does not exist, a partner that is down, a certificate that does not validate, or a server that belongs to someone else entirely. Shape validation is cheap, deterministic, and independent of the network, which is what makes it safe at startup. Reachability and trust are separate questions:

  • Reachability belongs to a dependency-specific health check or status signal. For an optional integration, report the partner's unavailability separately from application-wide readiness: some platforms take an instance out of traffic when its readiness check fails, which would stop unrelated features too. Include a dependency in readiness only when the application cannot safely do its intended work without it. Making host startup depend on a third party's availability turns their outage into yours.
  • Trust belongs to TLS certificate validation on the outbound connection, to an allow-list of permitted partner hosts when the setting can be influenced from outside the application's trusted deployment boundary, and to the authentication the partner requires. An allow-list should compare normalized host names and be backed by ordinary outbound-network controls; URI shape validation alone is not a defense against server-side request forgery.

That gives three separate operational decisions: startup validation asks whether the integration is configured correctly, dependency health asks whether the configured partner is available now, and application readiness asks whether this instance should receive traffic.

Reloads are not covered by ValidateOnStart

Some configuration providers can reload while the application runs. JSON files can be watched for changes, and other providers can signal changes of their own. The options documentation notes that validation runs again when options are reloaded. What you observe depends on which options interface reads the value and on whether that options instance has been created yet, and two tests make it concrete. Both simulate a provider change by setting a new value through IConfigurationRoot and then calling Reload(). Both behaviors were observed on .NET 10 with the synchronous validator used here; a later SDK, or asynchronous startup validation, may behave differently, so re-test before relying on the details.

In IOptionsKeepsTheFirstValueItReadAcrossAReload, one export uses the original endpoint, then the endpoint changes to another valid URL and the configuration reloads. The second export still uses the original endpoint, because IOptions<T> is a singleton that does not re-read configuration once it has been created. IOptionsMonitor<T>.CurrentValue reports the new endpoint. (IOptionsSnapshot<T>, which this sample does not use, is scoped: its value is computed on first access and cached for that scope, typically one HTTP request, so it suits scoped request-handling code, while IOptionsMonitor<T> is a singleton that background services can also use.)

In AnInvalidReloadFailsWhereTheValueIsReadNotAtStartup, the host starts successfully, then the endpoint changes to plain HTTP and the configuration reloads. The test shows both the failure and the recovery:

  • Reload() itself throws. In this test, the options monitor rebuilt and revalidated the options inside the reload notification, so the OptionsValidationException, wrapped in an AggregateException, went to the test's call to Reload(), and the started host remained running. A reload triggered by a file watcher was not tested; there the failure would likely surface on the provider's change-notification path, and how it is handled depends on the provider and the host.
  • Every read of IOptionsMonitor<T>.CurrentValue now throws.
  • The first export request fails with OptionsValidationException. This is the subtle part. ValidateOnStart validated the monitor's options instance during startup, while IOptions<T> keeps its own value, which had not been created yet. No request had read IOptions<T>.Value before the change, so the first one created that value from the changed configuration, validated it, and failed: exactly the failure startup validation was meant to prevent.
  • Both recover, by different routes. When the test restores a valid endpoint and reloads again, the reload replaces the monitor's entry, so IOptionsMonitor<T>.CurrentValue returns the valid endpoint; and because IOptions<T>.Value had never been created successfully, the next export creates it and succeeds.

The conclusion is not that reloading is broken. It is that someone has to own it. If a setting can change while the application runs, decide which interface reads it: IOptions<T> for "the value at first read, from then on", or IOptionsMonitor<T> for "the current value, revalidated". Decide what a failed reload should do (keep the last good value, alert, or stop the feature), and test that decision. Keeping the last good value is something the application has to implement; IOptionsMonitor<T> does not do it for you, as the test shows. If a setting must not change at runtime, don't enable reloading for its source.

Environment variables and Secret Manager are not vaults

The sample's API key arrives through an environment variable, because that is a common way for a deployment platform to hand a value to a process. That does not make the value secure. Microsoft's Secret Manager documentation warns that environment variables are often kept unencrypted, and that Secret Manager does not encrypt the secrets it stores and is meant only for development. Production secrets belong in a store designed for them, such as Azure Key Vault or your platform's equivalent, often surfaced to the application through a configuration provider. Validation can check that a secret is present; it cannot tell you whether it was handled safely on its way in.

Diagnostics That Name the Setting, Not the Value

Pulling the diagnostic rules together:

  • Validation messages name the key and the rule, never the value.
  • Binding failures can quote the raw value, as the .NET 10 conversion failure in this sample does. Where practical, bind sensitive settings as strings and validate them yourself.
  • Provider lookups report which provider won, not the value, and only when the provider's description is safe to log.
  • Do not dump the configuration to a log, an error page, or a diagnostics endpoint. If you must inspect it in a shared environment, GetDebugView has an overload that takes a function receiving each entry's context, including its key and value, and returns the text to print; use it to mask values.
  • Plant synthetic secrets in tests and assert their absence. A test that checks that the message mentions PartnerExport:Endpoint catches a vague message. Only a test that checks that the message does not contain SYNTHETIC-endpoint-secret-0000 catches a leak.

What the Tests Prove

The appendix contains eleven test methods, two of them parameterized theories, which run nineteen test cases. Each builds a real WebApplication on TestServer in the Production environment, which the test sets explicitly. Before adding its own sources, each test clears every configuration source the builder had added, so appsettings files, environment variables, and command-line arguments on the machine running the tests cannot change the bound options. Host settings the builder read before that point, such as the content root, are not covered by this isolation. The precedence test adds back JSON files it wrote itself and environment variables under a prefix unique to that run. A capturing logging provider records the log events delivered to it, including the host's startup-failure event. The export sender is a fake that records the endpoint it would have called; no test makes a network call.

Claim Test
Without validation, the host starts and the first export request fails with ArgumentNullException WithoutValidationTheAppStartsAndTheFirstExportFails
An environment variable overrides both JSON files; the winning provider is identified for four keys, and no description contains the values AHigherPrecedenceProviderOverridesTheCheckedInFiles
A disabled export starts with no endpoint, or with a rejected one, and returns 404 without sending ADisabledExportStartsWithoutAnAdmissibleEndpoint
An enabled export with a valid endpoint starts and sends to that endpoint AnEnabledExportWithAValidEndpointStartsAndUsesIt
Eight endpoints rejected by the policy each fail startup with one failure naming PartnerExport:Endpoint; no planted secret or endpoint value appears in the exception or the captured logs; no request reaches the application AnEnabledExportWithAPolicyRejectedEndpointFailsBeforeServingARequest
A missing endpoint, a missing API key, and an out-of-range timeout are reported together, in that order EveryUnmetRequirementIsReportedTogether
A value that cannot be converted fails startup as a binding failure, not a validation failure, and the binder's message and the startup log repeat the raw value AValueThatCannotBeConvertedIsABindingFailureNotAValidationFailure
A disabled export still fails startup when a value cannot be converted, because binding runs before the validator ADisabledExportStillHasToBind
A missing cosmetic setting uses its default and does not stop the application AMissingCosmeticSettingUsesItsDefault
An invalid reload after startup throws from Reload(), breaks IOptionsMonitor<T> reads, and fails the first request that builds IOptions<T>; restoring a valid value and reloading recovers both AnInvalidReloadFailsWhereTheValueIsReadNotAtStartup
IOptions<T> keeps the value it first read across a valid reload, while IOptionsMonitor<T> sees the new value IOptionsKeepsTheFirstValueItReadAcrossAReload

These tests do not prove that the partner endpoint is reachable or trustworthy, or that a real deployment platform stops a release when the host fails to start. They do not cover user secrets, command-line arguments, or the host-configuration fallback; the precedence test reproduces three of the default application-configuration layers. They do not exercise file-watching reloads, where the change notification comes from the file watcher rather than from the test's own call to Reload(). And they check diagnostics only in the exception and the logging pipeline the tests capture, not in other telemetry or crash reporting.

Continue Deeper

This article follows one optional integration from its providers to a startup check. Secure-by-Default ASP.NET Core Configuration treats configuration as a trust boundary across a whole application. Read it to choose between failing fast, failing closed, and degrading gracefully when a setting is missing; to decide who owns each configuration invariant; to keep development conveniences out of production; and to give secrets the custody they need rather than treating them as ordinary settings.

The sample's endpoint reads its options through the singleton IOptions<T> service, and the reload behavior above depends on which interface reads them. Your Dependency Injection Lifetime Is an Ownership Decision explains why choosing a lifetime decides who owns a value and for how long.


The Short Answer

A configuration defect can survive startup when nothing creates and validates the affected options at that stage. Review the composed configuration, not the files: later providers win, and in a default ASP.NET Core application an environment variable such as PartnerExport__Endpoint overrides both JSON files. To find which provider supplied a value, ask each provider whether it has the key, discard the retrieved value, and report a description of the winning provider that is safe to log.

Bind each optional integration to a typed options class with an explicit Enabled switch. Write one IValidateOptions<T> that checks nothing when the feature is disabled and, when it is enabled, reports every unmet requirement at once, naming settings and rules but never values. Register it with ValidateOnStart(), so an enabled feature with a rejected endpoint stops the host before it serves a request, while a disabled feature starts without one and a cosmetic setting falls back to its default. When a malformed setting could contain sensitive material, bind it as a string and validate it yourself, because a failed type conversion can quote the raw value.

Then be honest about the limits. A disabled feature skips your rules but not binding. A valid shape is not a reachable or trustworthy partner: check reachability with a dependency-specific health check, and trust with TLS and allow-lists. ValidateOnStart adds a validation step during host startup; it does not freeze the configuration or guarantee that later values stay valid, so decide who owns reloads. Keep production secrets in a real secret store, and plant synthetic secrets in your tests to verify that the diagnostic paths you test do not print them.


Appendix: Complete Code

The sample has two projects: an ASP.NET Core application project and a test project. Every file below was compiled and run as shown. The sample uses public .NET APIs and conventional ASP.NET Core registration patterns, but its application structure, sample code, tests, names, and explanatory comments were written for this article. It is offered under the MIT License, as described in the repository's licensing terms.

Environment used for verification

  • .NET SDK 10.0.404, target framework net10.0, on Windows x64, in the default Debug configuration.
  • xUnit v3 4.0.3, Microsoft.AspNetCore.TestHost 10.0.15, Microsoft.NET.Test.Sdk 18.12.0, and xunit.runner.visualstudio 4.0.1, each resolved at the pinned version. The command used Microsoft.Testing.Platform, which global.json selects for dotnet test on the .NET 10 SDK; the two VSTest packages remain for Visual Studio Test Explorer compatibility.
  • The recorded run used SDK 10.0.404. global.json permits any .NET 10 SDK from feature band 10.0.100 onward rather than requiring that exact SDK.
  • Warnings treated as errors, with the latest-recommended .NET analyzers; both projects built without warnings.
  • The command dotnet test --project Tests/OrdersApi.Tests.csproj, run from the folder that contains global.json, built both projects and reported 19 passing test cases (eleven test methods, two of them parameterized theories), with the same result on three consecutive runs.

Project files

global.json
App/OrdersApi.csproj
App/PartnerExport.cs
Tests/OrdersApi.Tests.csproj
Tests/Usings.cs
Tests/TestSupport.cs
Tests/ConfigurationStartupTests.cs

global.json:

{
  "sdk": {
    "version": "10.0.100",
    "rollForward": "latestFeature"
  },
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}

App/OrdersApi.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Library</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>

</Project>

Tests/OrdersApi.Tests.csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <OutputType>Exe</OutputType>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <AnalysisLevel>latest-recommended</AnalysisLevel>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="10.0.15" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0" />
    <PackageReference Include="xunit.v3" Version="4.0.3" />
    <PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <FrameworkReference Include="Microsoft.AspNetCore.App" />
    <ProjectReference Include="../App/OrdersApi.csproj" />
  </ItemGroup>

</Project>

Tests/Usings.cs:

global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Hosting;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Xunit;

The application project is a library here because the tests start it themselves. In a real application, Program.cs would call WebApplication.CreateBuilder(args), which adds the default configuration sources, then register AddPartnerExport() and a real IPartnerExportSender implementation (for example, one that uses an HttpClient with the configured timeout), build the application, and call MapPartnerExport(). A health check for the partner's reachability, if you want one, belongs in the same Program.cs, separate from the startup validation.

Application code

App/PartnerExport.cs:

using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;

namespace OrdersApi;

/// <summary>Settings for the optional nightly order export to a partner.</summary>
public sealed class PartnerExportOptions
{
    public const string SectionName = "PartnerExport";

    public bool Enabled { get; set; }

    public string? Endpoint { get; set; }

    public string? ApiKey { get; set; }

    public int TimeoutSeconds { get; set; } = 30;

    // Cosmetic: written into the export header. A default is harmless.
    public string SourceLabel { get; set; } = "orders-api";
}

/// <summary>
/// Checks the shape of the settings the export needs, only when the export is enabled.
/// Messages name settings; they never repeat a configured value.
/// </summary>
public sealed class PartnerExportOptionsValidator : IValidateOptions<PartnerExportOptions>
{
    private const string Section = PartnerExportOptions.SectionName;
    private const string EnabledKey = Section + ":" + nameof(PartnerExportOptions.Enabled);
    private const string EndpointKey = Section + ":" + nameof(PartnerExportOptions.Endpoint);
    private const string ApiKeyKey = Section + ":" + nameof(PartnerExportOptions.ApiKey);
    private const string TimeoutKey = Section + ":" + nameof(PartnerExportOptions.TimeoutSeconds);

    public ValidateOptionsResult Validate(string? name, PartnerExportOptions options)
    {
        ArgumentNullException.ThrowIfNull(options);

        if (!options.Enabled)
        {
            return ValidateOptionsResult.Success;
        }

        var failures = new List<string>();

        if (string.IsNullOrWhiteSpace(options.Endpoint))
        {
            failures.Add($"{EndpointKey} is required when {EnabledKey} is true.");
        }
        else if (!IsAdmissibleEndpoint(options.Endpoint))
        {
            failures.Add(
                $"{EndpointKey} must be an absolute HTTPS URI with a host and no user information, query, or fragment.");
        }

        if (string.IsNullOrWhiteSpace(options.ApiKey))
        {
            failures.Add($"{ApiKeyKey} is required when {EnabledKey} is true.");
        }

        if (options.TimeoutSeconds is < 1 or > 120)
        {
            failures.Add($"{TimeoutKey} must be between 1 and 120.");
        }

        return failures.Count == 0
            ? ValidateOptionsResult.Success
            : ValidateOptionsResult.Fail(failures);
    }

    // Shape only: says nothing about whether the host exists, answers, or can be trusted.
    private static bool IsAdmissibleEndpoint(string value) =>
        Uri.TryCreate(value, UriKind.Absolute, out var uri)
        && uri.Scheme == Uri.UriSchemeHttps
        && uri.Host.Length > 0
        && uri.UserInfo.Length == 0
        && uri.Query.Length == 0
        && uri.Fragment.Length == 0;
}

/// <summary>Sends one export. The real implementation would use HttpClient.</summary>
public interface IPartnerExportSender
{
    Task SendAsync(Uri endpoint, string apiKey, string sourceLabel, TimeSpan timeout, CancellationToken cancellationToken);
}

public static class PartnerExportFeature
{
    public static IServiceCollection AddPartnerExport(this IServiceCollection services)
    {
        services.AddOptions<PartnerExportOptions>()
            .BindConfiguration(PartnerExportOptions.SectionName)
            .ValidateOnStart();

        services.TryAddEnumerable(
            ServiceDescriptor.Singleton<IValidateOptions<PartnerExportOptions>, PartnerExportOptionsValidator>());

        return services;
    }

    public static IEndpointRouteBuilder MapPartnerExport(this IEndpointRouteBuilder endpoints)
    {
        endpoints.MapPost("/exports/orders", async (
            IOptions<PartnerExportOptions> options,
            IPartnerExportSender sender,
            CancellationToken cancellationToken) =>
        {
            var settings = options.Value;

            if (!settings.Enabled)
            {
                return Results.NotFound();
            }

            await sender.SendAsync(
                new Uri(settings.Endpoint!),
                settings.ApiKey!,
                settings.SourceLabel,
                TimeSpan.FromSeconds(settings.TimeoutSeconds),
                cancellationToken);

            return Results.Accepted();
        });

        return endpoints;
    }
}

/// <summary>Reports the highest-precedence provider that contains a key, without retaining or emitting its value.</summary>
public static class ConfigurationOrigin
{
    public static string? WinningProvider(IConfigurationRoot configuration, string key)
    {
        ArgumentNullException.ThrowIfNull(configuration);

        // Later providers win, so search from the last one added.
        foreach (var provider in configuration.Providers.Reverse())
        {
            if (provider.TryGet(key, out _))
            {
                return provider.ToString();
            }
        }

        return null;
    }
}

Test support

Tests/TestSupport.cs:

using System.Collections.Concurrent;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Logging;

namespace OrdersApi.Tests;

/// <summary>Planted values. Each is fake; the tests verify none appears in the exception or the captured logs.</summary>
internal static class Synthetic
{
    public const string ApiKey = "SYNTHETIC-export-key-0000";
    public const string EndpointSecret = "SYNTHETIC-endpoint-secret-0000";
}

internal sealed class RecordingSender : IPartnerExportSender
{
    public ConcurrentQueue<(Uri Endpoint, string SourceLabel)> Sent { get; } = new();

    public Task SendAsync(
        Uri endpoint, string apiKey, string sourceLabel, TimeSpan timeout, CancellationToken cancellationToken)
    {
        // No network call: the tests check which endpoint would be used, not whether it answers.
        Sent.Enqueue((endpoint, sourceLabel));
        return Task.CompletedTask;
    }
}

internal sealed class CapturingLoggerProvider : ILoggerProvider
{
    public ConcurrentQueue<string> Lines { get; } = new();

    public ILogger CreateLogger(string categoryName) => new CapturingLogger(Lines);

    public void Dispose()
    {
    }

    private sealed class CapturingLogger(ConcurrentQueue<string> lines) : ILogger
    {
        public IDisposable? BeginScope<TState>(TState state)
            where TState : notnull => null;

        public bool IsEnabled(LogLevel logLevel) => true;

        public void Log<TState>(
            LogLevel logLevel, EventId eventId, TState state, Exception? exception,
            Func<TState, Exception?, string> formatter)
        {
            lines.Enqueue($"{logLevel}: {formatter(state, exception)} {exception}");
        }
    }
}

/// <summary>
/// Builds the application on TestServer with configuration sources the test controls.
/// </summary>
internal sealed class TestApp : IAsyncDisposable
{
    private readonly RequestCounter _requests;

    private TestApp(WebApplication app, RecordingSender sender, CapturingLoggerProvider logs, RequestCounter requests)
    {
        App = app;
        Sender = sender;
        Logs = logs;
        _requests = requests;
    }

    public WebApplication App { get; }

    public RecordingSender Sender { get; }

    public CapturingLoggerProvider Logs { get; }

    public int RequestsSeen => _requests.Count;

    public static TestApp Create(
        Action<IConfigurationBuilder> addSources,
        Action<IServiceCollection>? registerExport = null)
    {
        var builder = WebApplication.CreateBuilder(
            new WebApplicationOptions { EnvironmentName = Environments.Production });

        // Isolation: remove every configuration source the builder added (appsettings files,
        // environment variables, command line) so values on the machine running the tests cannot
        // change the bound options. Host settings read before this point are not affected.
        builder.Configuration.Sources.Clear();
        addSources(builder.Configuration);

        builder.WebHost.UseTestServer();

        var logs = new CapturingLoggerProvider();
        builder.Logging.ClearProviders();
        builder.Logging.AddProvider(logs);

        var sender = new RecordingSender();
        builder.Services.AddSingleton<IPartnerExportSender>(sender);
        (registerExport ?? (services => services.AddPartnerExport()))(builder.Services);

        var app = builder.Build();

        var requests = new RequestCounter();
        app.Use(next => context =>
        {
            requests.Increment();
            return next(context);
        });
        app.MapPartnerExport();

        return new TestApp(app, sender, logs, requests);
    }

    public static TestApp FromSettings(
        IReadOnlyDictionary<string, string?> settings,
        Action<IServiceCollection>? registerExport = null) =>
        Create(configuration => configuration.AddInMemoryCollection(settings), registerExport);

    public async Task<HttpResponseMessage> PostExportAsync()
    {
        using var client = App.GetTestClient();
        return await client.PostAsync(new Uri("/exports/orders", UriKind.Relative), content: null);
    }

    /// <summary>The startup exception and the log events this test captured.</summary>
    public string Diagnostics(Exception startupFailure) =>
        startupFailure + Environment.NewLine + string.Join(Environment.NewLine, Logs.Lines);

    public async ValueTask DisposeAsync() => await App.DisposeAsync();

    private sealed class RequestCounter
    {
        private int _count;

        public int Count => Volatile.Read(ref _count);

        public void Increment() => Interlocked.Increment(ref _count);
    }
}

internal static class Settings
{
    public const string ValidEndpoint = "https://partner.example.com/v2/orders";

    public static Dictionary<string, string?> EnabledWith(string? endpoint, string? apiKey = Synthetic.ApiKey)
    {
        var settings = new Dictionary<string, string?> { ["PartnerExport:Enabled"] = "true" };

        if (endpoint is not null)
        {
            settings["PartnerExport:Endpoint"] = endpoint;
        }

        if (apiKey is not null)
        {
            settings["PartnerExport:ApiKey"] = apiKey;
        }

        return settings;
    }
}

Tests

Tests/ConfigurationStartupTests.cs:

using Microsoft.Extensions.Options;

namespace OrdersApi.Tests;

public sealed class ConfigurationStartupTests
{
    private static CancellationToken Cancel => TestContext.Current.CancellationToken;

    [Fact]
    public async Task WithoutValidationTheAppStartsAndTheFirstExportFails()
    {
        // The registration from the opening: binds the section, validates nothing.
        await using var test = TestApp.FromSettings(
            Settings.EnabledWith(endpoint: null),
            services => services.AddOptions<PartnerExportOptions>().BindConfiguration(PartnerExportOptions.SectionName));

        await test.App.StartAsync(Cancel);

        var failure = await Record.ExceptionAsync(test.PostExportAsync);

        Assert.IsType<ArgumentNullException>(failure);
        Assert.Equal(1, test.RequestsSeen);
        Assert.Empty(test.Sender.Sent);
    }

    [Fact]
    public async Task AHigherPrecedenceProviderOverridesTheCheckedInFiles()
    {
        var folder = Directory.CreateTempSubdirectory("orders-api-config-");
        var prefix = $"ORDERSAPI_TEST_{Guid.NewGuid():N}_";
        const string overridden = "https://partner-eu.example.com/v2/orders";

        try
        {
            await File.WriteAllTextAsync(
                Path.Combine(folder.FullName, "appsettings.json"),
                """{ "PartnerExport": { "Enabled": false, "Endpoint": "https://partner.example.com/v1/orders", "TimeoutSeconds": 30 } }""",
                Cancel);
            await File.WriteAllTextAsync(
                Path.Combine(folder.FullName, "appsettings.Production.json"),
                """{ "PartnerExport": { "Enabled": true, "Endpoint": "https://partner.example.com/v2/orders" } }""",
                Cancel);

            // A unique prefix keeps any variable already on the machine out of this test.
            Environment.SetEnvironmentVariable($"{prefix}PartnerExport__Endpoint", overridden);
            Environment.SetEnvironmentVariable($"{prefix}PartnerExport__ApiKey", Synthetic.ApiKey);

            // The same order WebApplication.CreateBuilder uses, without user secrets or the command line.
            await using var test = TestApp.Create(configuration => configuration
                .SetBasePath(folder.FullName)
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                .AddJsonFile("appsettings.Production.json", optional: true, reloadOnChange: false)
                .AddEnvironmentVariables(prefix));

            await test.App.StartAsync(Cancel);

            var options = test.App.Services.GetRequiredService<IOptions<PartnerExportOptions>>().Value;
            Assert.Equal(overridden, options.Endpoint);

            var root = (IConfigurationRoot)test.App.Configuration;
            var endpointOrigin = ConfigurationOrigin.WinningProvider(root, "PartnerExport:Endpoint");
            var enabledOrigin = ConfigurationOrigin.WinningProvider(root, "PartnerExport:Enabled");
            var timeoutOrigin = ConfigurationOrigin.WinningProvider(root, "PartnerExport:TimeoutSeconds");
            var apiKeyOrigin = ConfigurationOrigin.WinningProvider(root, "PartnerExport:ApiKey");

            // These checks on descriptions verify the test; application code should not parse them.
            Assert.StartsWith("EnvironmentVariablesConfigurationProvider", endpointOrigin, StringComparison.Ordinal);
            Assert.Contains("appsettings.Production.json", enabledOrigin, StringComparison.Ordinal);
            Assert.Contains("'appsettings.json'", timeoutOrigin, StringComparison.Ordinal);
            Assert.StartsWith("EnvironmentVariablesConfigurationProvider", apiKeyOrigin, StringComparison.Ordinal);

            foreach (var origin in new[] { endpointOrigin, enabledOrigin, timeoutOrigin, apiKeyOrigin })
            {
                Assert.DoesNotContain(Synthetic.ApiKey, origin, StringComparison.Ordinal);
                Assert.DoesNotContain("partner-eu", origin, StringComparison.Ordinal);
            }

            using var response = await test.PostExportAsync();
            Assert.Equal(System.Net.HttpStatusCode.Accepted, response.StatusCode);
            Assert.Equal(new Uri(overridden), Assert.Single(test.Sender.Sent).Endpoint);
        }
        finally
        {
            Environment.SetEnvironmentVariable($"{prefix}PartnerExport__Endpoint", null);
            Environment.SetEnvironmentVariable($"{prefix}PartnerExport__ApiKey", null);
            folder.Delete(recursive: true);
        }
    }

    [Theory]
    [InlineData(null)]
    [InlineData("not a url")]
    public async Task ADisabledExportStartsWithoutAnAdmissibleEndpoint(string? endpoint)
    {
        var settings = new Dictionary<string, string?> { ["PartnerExport:Enabled"] = "false" };
        if (endpoint is not null)
        {
            settings["PartnerExport:Endpoint"] = endpoint;
        }

        await using var test = TestApp.FromSettings(settings);

        await test.App.StartAsync(Cancel);
        using var response = await test.PostExportAsync();

        Assert.Equal(System.Net.HttpStatusCode.NotFound, response.StatusCode);
        Assert.Empty(test.Sender.Sent);
    }

    [Fact]
    public async Task AnEnabledExportWithAValidEndpointStartsAndUsesIt()
    {
        await using var test = TestApp.FromSettings(Settings.EnabledWith(Settings.ValidEndpoint));

        await test.App.StartAsync(Cancel);
        using var response = await test.PostExportAsync();

        Assert.Equal(System.Net.HttpStatusCode.Accepted, response.StatusCode);
        var sent = Assert.Single(test.Sender.Sent);
        Assert.Equal(new Uri(Settings.ValidEndpoint), sent.Endpoint);
    }

    [Theory]
    [InlineData(null)]
    [InlineData("partner.example.com/v2/orders")]
    [InlineData("http://partner.example.com/v2/orders")]
    [InlineData($"https://svc-orders:{Synthetic.EndpointSecret}@partner.example.com/v2/orders")]
    [InlineData($"https://partner.example.com/v2/orders?token={Synthetic.EndpointSecret}")]
    [InlineData($"https://partner.example.com/v2/orders#{Synthetic.EndpointSecret}")]
    [InlineData("https://partner.example.com/v2/orders?")]
    [InlineData("https://partner.example.com/v2/orders#")]
    public async Task AnEnabledExportWithAPolicyRejectedEndpointFailsBeforeServingARequest(string? endpoint)
    {
        await using var test = TestApp.FromSettings(Settings.EnabledWith(endpoint));

        var failure = await Assert.ThrowsAsync<OptionsValidationException>(() => test.App.StartAsync(Cancel));

        Assert.Contains("PartnerExport:Endpoint", Assert.Single(failure.Failures), StringComparison.Ordinal);

        var diagnostics = test.Diagnostics(failure);
        Assert.DoesNotContain(Synthetic.ApiKey, diagnostics, StringComparison.Ordinal);
        Assert.DoesNotContain(Synthetic.EndpointSecret, diagnostics, StringComparison.Ordinal);
        if (endpoint is not null)
        {
            Assert.DoesNotContain(endpoint, diagnostics, StringComparison.Ordinal);
        }

        // The server never started, so no request reached the application.
        await Assert.ThrowsAnyAsync<Exception>(test.PostExportAsync);
        Assert.Equal(0, test.RequestsSeen);
        Assert.Empty(test.Sender.Sent);
    }

    [Fact]
    public async Task ADisabledExportStillHasToBind()
    {
        // The validator skips a disabled export, but binding runs first and does not.
        var settings = new Dictionary<string, string?>
        {
            ["PartnerExport:Enabled"] = "false",
            ["PartnerExport:TimeoutSeconds"] = "thirty",
        };
        await using var test = TestApp.FromSettings(settings);

        var failure = await Assert.ThrowsAsync<InvalidOperationException>(() => test.App.StartAsync(Cancel));

        Assert.IsNotType<OptionsValidationException>(failure);
        Assert.Contains("PartnerExport:TimeoutSeconds", failure.Message, StringComparison.Ordinal);
        Assert.Equal(0, test.RequestsSeen);
        Assert.Empty(test.Sender.Sent);
    }

    [Fact]
    public async Task EveryUnmetRequirementIsReportedTogether()
    {
        var settings = Settings.EnabledWith(endpoint: null, apiKey: null);
        settings["PartnerExport:TimeoutSeconds"] = "0";
        await using var test = TestApp.FromSettings(settings);

        var failure = await Assert.ThrowsAsync<OptionsValidationException>(() => test.App.StartAsync(Cancel));

        Assert.Collection(
            failure.Failures,
            message => Assert.StartsWith("PartnerExport:Endpoint ", message, StringComparison.Ordinal),
            message => Assert.StartsWith("PartnerExport:ApiKey ", message, StringComparison.Ordinal),
            message => Assert.StartsWith("PartnerExport:TimeoutSeconds ", message, StringComparison.Ordinal));
    }

    [Fact]
    public async Task AValueThatCannotBeConvertedIsABindingFailureNotAValidationFailure()
    {
        var settings = Settings.EnabledWith(Settings.ValidEndpoint);
        settings["PartnerExport:TimeoutSeconds"] = "thirty";
        await using var test = TestApp.FromSettings(settings);

        var failure = await Assert.ThrowsAsync<InvalidOperationException>(() => test.App.StartAsync(Cancel));

        Assert.IsNotType<OptionsValidationException>(failure);
        Assert.Contains("PartnerExport:TimeoutSeconds", failure.Message, StringComparison.Ordinal);
        Assert.Contains("System.Int32", failure.Message, StringComparison.Ordinal);

        // Unlike the validator's messages, the binder's message repeats the raw value,
        // and the host's startup-failure log repeats the exception.
        Assert.Contains("'thirty'", failure.Message, StringComparison.Ordinal);
        Assert.Contains(test.Logs.Lines, line => line.Contains("'thirty'", StringComparison.Ordinal));
        Assert.DoesNotContain(Synthetic.ApiKey, test.Diagnostics(failure), StringComparison.Ordinal);
        Assert.Equal(0, test.RequestsSeen);
    }

    [Fact]
    public async Task AMissingCosmeticSettingUsesItsDefault()
    {
        await using var test = TestApp.FromSettings(Settings.EnabledWith(Settings.ValidEndpoint));

        await test.App.StartAsync(Cancel);
        using var response = await test.PostExportAsync();

        Assert.Equal(System.Net.HttpStatusCode.Accepted, response.StatusCode);
        Assert.Equal("orders-api", Assert.Single(test.Sender.Sent).SourceLabel);
    }

    [Fact]
    public async Task AnInvalidReloadFailsWhereTheValueIsReadNotAtStartup()
    {
        await using var test = TestApp.FromSettings(Settings.EnabledWith(Settings.ValidEndpoint));
        await test.App.StartAsync(Cancel);

        // Simulate a configuration source changing after a successful start by setting a value
        // through the configuration root.
        var root = (IConfigurationRoot)test.App.Configuration;
        root["PartnerExport:Endpoint"] = "http://partner.example.com/v2/orders";

        // In this test the options monitor revalidates inside the reload notification, so the
        // failure goes to the caller of Reload(), and the started host remains running.
        var reloadFailure = Assert.Throws<AggregateException>(root.Reload);
        var validation = Assert.IsType<OptionsValidationException>(Assert.Single(reloadFailure.InnerExceptions));
        Assert.Contains("PartnerExport:Endpoint", Assert.Single(validation.Failures), StringComparison.Ordinal);

        var monitor = test.App.Services.GetRequiredService<IOptionsMonitor<PartnerExportOptions>>();
        Assert.Throws<OptionsValidationException>(() => monitor.CurrentValue);

        // No request had read IOptions<T>.Value yet, so the first one creates that value from the
        // changed configuration, validates it, and fails: the failure ValidateOnStart was added to prevent.
        await Assert.ThrowsAsync<OptionsValidationException>(test.PostExportAsync);
        Assert.Empty(test.Sender.Sent);

        // Fixing the value and reloading again recovers both. The reload replaces the monitor's
        // entry; IOptions<T>.Value was never created, so its next read creates it.
        root["PartnerExport:Endpoint"] = Settings.ValidEndpoint;
        root.Reload();

        Assert.Equal(Settings.ValidEndpoint, monitor.CurrentValue.Endpoint);
        using var response = await test.PostExportAsync();
        Assert.Equal(System.Net.HttpStatusCode.Accepted, response.StatusCode);
        Assert.Equal(new Uri(Settings.ValidEndpoint), Assert.Single(test.Sender.Sent).Endpoint);
    }

    [Fact]
    public async Task IOptionsKeepsTheFirstValueItReadAcrossAReload()
    {
        await using var test = TestApp.FromSettings(Settings.EnabledWith(Settings.ValidEndpoint));
        await test.App.StartAsync(Cancel);

        using (var first = await test.PostExportAsync())
        {
            Assert.Equal(System.Net.HttpStatusCode.Accepted, first.StatusCode);
        }

        const string moved = "https://partner-eu.example.com/v2/orders";
        var root = (IConfigurationRoot)test.App.Configuration;
        root["PartnerExport:Endpoint"] = moved;
        root.Reload();

        using (var second = await test.PostExportAsync())
        {
            Assert.Equal(System.Net.HttpStatusCode.Accepted, second.StatusCode);
        }

        // The endpoint reads IOptions<T>, which never sees the reload; the monitor does.
        Assert.All(test.Sender.Sent, sent => Assert.Equal(new Uri(Settings.ValidEndpoint), sent.Endpoint));
        var monitor = test.App.Services.GetRequiredService<IOptionsMonitor<PartnerExportOptions>>();
        Assert.Equal(moved, monitor.CurrentValue.Endpoint);
    }
}