Skip to content

Async Options Validation at Startup in .NET 11

Learn how to validate options asynchronously at startup in .NET 11 with IAsyncValidateOptions and the new async Validate overloads, so your application fails fast when a configured endpoint is unreachable or misconfigured.

Ivan GechevIvan GechevSoftware Developer
Published on
Reading time
12 min read
On this page

In my What Is the Options Pattern and How to Easily Mock IOptions article, we saw how to validate our settings with data annotations, custom Validate() delegates, and the ValidateOnStart() method. This catches missing values, typos in section names, and values out of range before our application serves a single request.

But some configuration problems can't be caught by looking at the values alone. A base URL can be a perfectly valid URL and still point to the wrong host. An API key can be exactly 32 characters long and still be expired. To find these issues, we have to actually call something, and that means doing I/O.

Until now, options validation was strictly synchronous. .NET 11 changes that by adding async options validation, including at startup. Our application can now check that its configuration actually works and refuse to start if it doesn't.

In this article, we'll look at why the old approaches weren't great, then we'll add async validation with a simple delegate, move on to a dedicated validator class, and finish with some important caveats about when async validation runs and when it doesn't. As usual, we'll keep things cat-themed, so we'll validate the configuration of a cat facts API.

Let's dive in!

The Problem With Validating Configuration Over the Network

Our application calls an external cat facts API. Its configuration looks like this:

appsettings.json
JSON
{
  "CatFactsApi": {
    "BaseUrl": "https://catfact.ninja",
    "HealthCheckPath": "/fact",
    "StartupCheckTimeoutSeconds": 5
  }
}

And the matching options class:

CatFactsApiOptions.cs
C#
public sealed class CatFactsApiOptions
{
	public const string SectionName = "CatFactsApi";

	[Required, Url]
	public required string BaseUrl { get; init; }

	[Required]
	public required string HealthCheckPath { get; init; }

	[Range(1, 30)]
	public int StartupCheckTimeoutSeconds { get; init; } = 5;
}

We use data annotations to make sure the BaseUrl is a valid URL, the HealthCheckPath isn't empty, and the timeout is within a reasonable range.

Now, imagine somebody deploys our application with https://catfacts.ninja instead of https://catfact.ninja. It's still a valid URL, so our data annotations are happy. The application starts, reports itself as healthy, and fails on the first request that needs a cat fact.

Before .NET 11, if we wanted to catch this at startup, we had two not-so-great options:

  • Call the API inside a synchronous Validate() delegate and block on it with .GetAwaiter().GetResult()
  • Write a custom IHostedService that checks the configuration in its StartAsync() method

The first one is sync-over-async, which blocks a thread and is a known source of deadlocks. The second one works, but it splits our validation logic in two places, and it reports failures differently than the rest of our options validation.

Async Validation With a Delegate

The quickest way to add an async rule in .NET 11 is with the new async overloads of the Validate() method:

Program.cs
C#
builder.Services.AddHttpClient();

builder.Services.AddOptions<CatFactsApiOptions>()
	.BindConfiguration(CatFactsApiOptions.SectionName)
	.ValidateDataAnnotations()
	.Validate<IHttpClientFactory>(async (options, httpClientFactory, cancellationToken) =>
	{
		if (!Uri.TryCreate(options.BaseUrl, UriKind.Absolute, out var baseUrl))
		{
			return true; // Invalid URLs are reported by the data annotations
		}

		var client = httpClientFactory.CreateClient();
		var healthCheckUrl = new Uri(baseUrl, options.HealthCheckPath);

		try
		{
			using var response = await client.GetAsync(healthCheckUrl, cancellationToken);

			return response.IsSuccessStatusCode;
		}
		catch (HttpRequestException)
		{
			return false;
		}
	}, "The Cat Facts API isn't reachable with the configured BaseUrl.")
	.ValidateOnStart();

We register the IHttpClientFactory with the AddHttpClient() method first, as we need it to make HTTP calls.

Then, we bind and validate our options as we normally would. The new part is the Validate<IHttpClientFactory>() call. In .NET 11, the Validate() method has overloads that accept a Func<TOptions, CancellationToken, Task<bool>> delegate. The versions with type parameters, like ours, also resolve up to five dependencies from the DI container for us.

Inside the delegate, we first make sure the BaseUrl can be parsed. If it can't, we let the check pass, as the [Url] attribute already reports that problem. Then, we build the health check URL and send a GET request. If the API responds with a success status code, the validation passes. If it responds with an error, or we can't reach it at all, the validation fails with the message we pass as the second argument.

Finally, the ValidateOnStart() call is what makes all of this work. Async options validation only runs during startup. Without ValidateOnStart(), our async delegate never gets a chance to run, but more on that later.

Now, if we start our application with a wrong BaseUrl, it doesn't start at all:

Unhandled exception. Microsoft.Extensions.Options.OptionsValidationException: The Cat Facts API isn't reachable with the configured BaseUrl.

The host throws an OptionsValidationException with our failure message, and our application never starts listening for requests.

If you are interested in having a deep dive into Minimal APIs, you can check my Minimal APIs in ASP.NET Core course here.

Delegates are great for short checks, but our startup logic is already growing. Let's move it to a dedicated class.

Async Validation With IAsyncValidateOptions

For anything more than a few lines, I prefer a dedicated validator class. .NET 11 introduces the IAsyncValidateOptions<TOptions> interface for exactly this:

CatFactsApiOptionsValidator.cs
C#
public sealed class CatFactsApiOptionsValidator(IHttpClientFactory httpClientFactory)
	: IAsyncValidateOptions<CatFactsApiOptions>
{
	public async Task<ValidateOptionsResult> ValidateAsync(
		string? name,
		CatFactsApiOptions options,
		CancellationToken cancellationToken = default)
	{
		if (!Uri.TryCreate(options.BaseUrl, UriKind.Absolute, out var baseUrl))
		{
			return ValidateOptionsResult.Skip;
		}

		using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
		timeout.CancelAfter(TimeSpan.FromSeconds(options.StartupCheckTimeoutSeconds));

		var client = httpClientFactory.CreateClient();
		var healthCheckUrl = new Uri(baseUrl, options.HealthCheckPath);

		try
		{
			using var response = await client.GetAsync(healthCheckUrl, timeout.Token);

			return response.IsSuccessStatusCode
				? ValidateOptionsResult.Success
				: ValidateOptionsResult.Fail(
					$"The Cat Facts API at '{healthCheckUrl}' returned {(int)response.StatusCode}.");
		}
		catch (HttpRequestException ex)
		{
			return ValidateOptionsResult.Fail(
				$"The Cat Facts API at '{healthCheckUrl}' isn't reachable: {ex.Message}");
		}
		catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
		{
			return ValidateOptionsResult.Fail(
				$"The Cat Facts API at '{healthCheckUrl}' didn't respond within {options.StartupCheckTimeoutSeconds} seconds.");
		}
	}

	public ValidateOptionsResult Validate(string? name, CatFactsApiOptions options) =>
		ValidateOptionsResult.Fail(
			$"{nameof(CatFactsApiOptions)} must be validated asynchronously at startup.");
}

There's quite a bit going on here, so let's break it down.

We implement the IAsyncValidateOptions<CatFactsApiOptions> interface and use a primary constructor to inject the IHttpClientFactory. Validator classes are resolved from the DI container, so we can inject anything we need.

In the ValidateAsync() method, we first make sure the BaseUrl is a valid absolute URL. If it isn't, we return ValidateOptionsResult.Skip. Reporting invalid URLs is the job of our data annotations, and we don't want to report a second, confusing error for the same problem.

Next, we create a linked CancellationTokenSource and cancel it after the configured timeout. This is important. A health check that hangs for 100 seconds, which is the default HttpClient timeout, would make our application hang for 100 seconds at startup. With our own timeout, we fail fast.

Then, we send the request and turn every possible outcome into a meaningful ValidateOptionsResult. A non-success status code, a network error, and a timeout each get their own message, which makes troubleshooting a failed deployment so much easier. Here's what each of them looks like at startup:

OptionsValidationException: The Cat Facts API at 'https://catfacts.ninja/fact' isn't reachable: No such host is known. (catfacts.ninja:443)
OptionsValidationException: The Cat Facts API at 'https://catfact.ninja/nope' returned 404.
OptionsValidationException: The Cat Facts API at 'http://10.255.255.1/fact' didn't respond within 2 seconds.
``` Note the `when` filter on the last `catch` block. We only treat the cancellation as a timeout if it was our token that fired, and not the one the framework passed to us.

### Why Does Validate() Return a Failure?

`IAsyncValidateOptions<TOptions>` inherits from the good old `IValidateOptions<TOptions>` interface, so we also have to implement the synchronous `Validate()` method.

The framework never calls both methods for the same validation. Async options creation calls `ValidateAsync()`, while synchronous options creation calls `Validate()`. If a rule can't run synchronously, Microsoft's guidance is to return a failed result. **Never return `Success` from the synchronous fallback**, as that would silently skip your check.

If you've read my [Async Validation in .NET 11 Minimal APIs](https://ivangechev.com/blog/minimal-apis/async-validation-in-net-11-minimal-apis) article, this will feel very familiar. It's the same idea as throwing from the synchronous `IsValid()` method, just with a result instead of an exception.

### Registering the Validator

We register our validator as an `IValidateOptions<CatFactsApiOptions>`:
```CSharp:Program.cs
builder.Services.AddHttpClient();

builder.Services.AddOptions<CatFactsApiOptions>()
	.BindConfiguration(CatFactsApiOptions.SectionName)
	.ValidateDataAnnotations()
	.ValidateOnStart();

builder.Services.AddSingleton<IValidateOptions<CatFactsApiOptions>, CatFactsApiOptionsValidator>();

Note that we don't register it as IAsyncValidateOptions<CatFactsApiOptions>. The options infrastructure looks for IValidateOptions<TOptions> registrations and detects the async interface on its own. The docs are explicit here: async validators must be registered as IValidateOptions<TOptions> or through the Validate<TValidateOptions>() method, not directly as IAsyncValidateOptions<TOptions>.

That Validate<TValidateOptions>() method is another .NET 11 addition to the OptionsBuilder<TOptions> class. It scopes the validator to the options name of that builder, which is useful if you work with named options.

Async Data Annotations in Options

Since .NET 11 supports async validation attributes, you might be wondering if you can use an AsyncValidationAttribute on an options class. You can, and the ValidateDataAnnotations() method supports them.

But the same rule applies: async attributes only run asynchronously during startup, when ValidateOnStart() is called. Without it, accessing the options only triggers synchronous validation, which calls the attribute's synchronous IsValid() fallback instead.

For options, I prefer a validator class over an async attribute. Startup checks usually need configuration from several properties and a few services, and a class gives us much more room for clear error messages.

When Async Validation Runs and When It Doesn't

This is the most important part of this article. Async options validation is built around startup, and it comes with some limitations you should know about before using it.

Only IOptions and IOptionsMonitor Get the Validated Value

During startup, the async validation seeds the built-in IOptions<TOptions> and IOptionsMonitor<TOptions> caches with the validated value. Later, when we inject IOptions<CatFactsApiOptions> anywhere in our application, we get that cached instance, and no validation runs again.

IOptionsSnapshot<TOptions> is a different story. It always validates synchronously and isn't populated by startup validation. With our validator, the synchronous fallback returns a failure, so every request that resolves IOptionsSnapshot<CatFactsApiOptions> throws an OptionsValidationException:

Microsoft.Extensions.Options.OptionsValidationException: Options instance of type 'CatFactsApiOptions' is validated by an asynchronous validator that cannot run during synchronous validation.

Notice that this message comes from the framework, not from our fallback. The options infrastructure detects async validators and refuses to create the value synchronously. This happens with the async Validate() delegates as well, so if you use async validation, stick to IOptions<TOptions>.

Reloads Are Synchronous

IOptionsMonitor<TOptions> reloads options synchronously when the configuration changes, and it never calls async validation. With a validator like ours, a reload will fail, and change listeners won't be notified.

In practice, this means async validation is a great fit for options that are set once per deployment, like base URLs and API keys. It's not a good fit for options you expect to change while the application is running.

Don't Access the Options Before Startup Completes

Options that need async validation can't be accessed synchronously before startup completes. For example, if you read IOptions<CatFactsApiOptions>.Value in your Program class before calling app.Run(), the value is created synchronously, our synchronous fallback runs, and it fails.

Custom Options Infrastructure Opts You Out

If you replace the default IOptionsFactory<TOptions>, it only performs synchronous validation and never calls ValidateAsync(). A custom IOptions<TOptions> implementation isn't supported for default-name async validation at all, and startup throws an InvalidOperationException. Most applications never replace these, but it's good to know.

Should Your Application Refuse to Start?

Async startup validation is a powerful tool, but it's worth thinking about what we're actually validating.

There's a difference between configuration that is wrong and a dependency that is temporarily down. A wrong host name, a 401 Unauthorized because of an invalid API key, or a 404 Not Found because of a wrong path are configuration problems. They won't fix themselves, so failing fast is exactly what we want.

A timeout or a 503 Service Unavailable is different. If the cat facts API is down for five minutes, should our application refuse to start? In Kubernetes or Azure Container Apps, that can lead to crash loops and make an outage worse. Our application might also have other features that work perfectly fine without cat facts.

My recommendation is to use startup validation for things that prove the configuration is correct, and health checks for things that tell you whether a dependency is available right now. If your validator treats transient errors as failures, make sure that's a conscious decision.

The same idea works for the Azure services we've covered on this blog. You can check that a Key Vault URI resolves and that your credential has access, or that an Azure OpenAI deployment name actually exists, before your application accepts traffic.

What About IStartupValidator?

If you've implemented the IStartupValidator interface yourself in the past, you'll notice that it's now obsolete in .NET 11, and you'll get the SYSLIB0066 warning. Its replacement is the new IAsyncStartupValidator interface, which has a single ValidateAsync(CancellationToken) method.

Be careful with old implementations. A custom validator that is registered only as an IStartupValidator takes precedence over the built-in one and suppresses all asynchronous startup validators. So if your async validators never seem to run, this is one of the first things to check.

Conclusion

Async options validation closes one of the last gaps in the options pattern. With the new async Validate() overloads and the IAsyncValidateOptions<TOptions> interface, our applications can check that their configuration actually works, and fail fast with a clear message when it doesn't, all without sync-over-async hacks or custom hosted services.

Just remember that async validation is built around startup. Call ValidateOnStart(), inject IOptions<TOptions> instead of IOptionsSnapshot<TOptions>, and use it for settings that don't change while your application is running.

Frequently Asked Questions

Does async options validation run without ValidateOnStart()?

No. Async validation runs during startup. Without ValidateOnStart(), accessing the options only triggers synchronous validation.

What exception do I get when async validation fails?

An OptionsValidationException. When several validators fail for the same options type, for example, a data annotation and our async check, their messages are combined into a single OptionsValidationException, separated by semicolons.

Can I use IOptionsSnapshot<TOptions> with async validators?

Not reliably. IOptionsSnapshot<TOptions> always validates synchronously and isn't populated by startup validation, so it calls your synchronous fallback on every request.

How do I register an async options validator?

Register it as IValidateOptions<TOptions>, or use the Validate<TValidateOptions>() method on the OptionsBuilder<TOptions>. Don't register it directly as IAsyncValidateOptions<TOptions>.

Can I inject services into an async validator?

Yes. Validator classes are resolved from the DI container, and the async Validate() overloads on OptionsBuilder<TOptions> can resolve up to five dependencies for you.

What should the synchronous Validate() method return in an async validator?

A failed result if the rule can't run synchronously. Never return Success, as that would silently skip your check.

> keep reading

13 min read

Async Validation in .NET 11 Minimal APIs

Learn how to use the new async validation support in .NET 11 Minimal APIs with AsyncValidationAttribute and IAsyncValidatableObject to run database-backed validation rules before your endpoint handlers even execute.