Skip to content

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.

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

In my How to Validate Incoming Requests in .NET 10 Minimal APIs post, we explored the brand new built-in validation for Minimal APIs. Data annotations, IValidatableObject, ProblemDetails responses, all working out of the box with a single call to AddValidation(). It was a huge step forward.

But there was one big gap. Everything had to be synchronous. The moment a validation rule needed to talk to a database or call another API, like checking if a cat with that name already exists, we were back to putting if statements in our endpoint handlers.

.NET 11 closes that gap by introducing async validation support. We can now write validation attributes and validatable objects that we can await and the framework runs them automatically before our handlers even execute.

In this article, we'll first look at the problem in .NET 10, then build an async validation attribute, move on to object-level async validation with IAsyncValidatableObject, and finish with some points you should know about before using this in production. As usual, we'll use a cat-themed API to demonstrate each concept.

Let's dive in!

The Problem With Async Rules in .NET 10

Let's say our cat API has a rule: we only accept breeds that exist in our breed registry. The registry lives in a database, so checking it is an async operation.

In .NET 10, data annotations can't await anything. So the only clean option is to move that check into the handler (or a separate filter or service). Here's what that looks like:

Program.cs
C#
catRoutes.MapPost("", async (
    CreateCatRequest request,
    IBreedRegistry breedRegistry,
    CancellationToken cancellationToken) =>
{
    if (!await breedRegistry.ExistsAsync(request.Breed, cancellationToken))
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            [nameof(CreateCatRequest.Breed)] = [$"'{request.Breed}' is not a known breed."]
        });
    }

    return Results.Created($"/api/cats/{Random.Shared.Next(1, 999)}", request);
});

This works, but look at what happened to our nice and clean handler. It now has to inject a service it doesn't really need for its business logic, build a validation error dictionary by hand, and return a validation problem response. On top of that, our validation rules are now split between the model (data annotations) and the handler (async checks).

And this logic has to be repeated in every endpoint that accepts a breed. Not ideal.

Getting Started With Async Validation in .NET 11

The good news is that the setup is exactly the same as in .NET 10. We need a project targeting net11.0 and a single line in our Program class:

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

There's no extra NuGet package to install. The new async validation APIs ship with the ASP.NET Core shared framework.

Before we write any validation, let's create the service our rules will use. For this demo, we'll keep things simple and use an in-memory implementation:

BreedRegistry.cs
C#
public interface IBreedRegistry
{
    Task<bool> ExistsAsync(
        string breed,
        CancellationToken cancellationToken);
}

public sealed class InMemoryBreedRegistry : IBreedRegistry
{
    private static readonly HashSet<string> Breeds =
        new(StringComparer.OrdinalIgnoreCase)
        {
            "Maine Coon",
            "British Shorthair",
            "Siamese",
             "Persian",
            "Domestic Shorthair"
        };

    public async Task<bool> ExistsAsync(
        string breed,
        CancellationToken cancellationToken)
    {
        // A small delay to simulate a database call
        await Task.Delay(50, cancellationToken);

        return Breeds.Contains(breed);
    }
}

We use the Task.Delay() method to simulate a database call, so we have something to actually await.

Then, we register it in the DI container:

Program.cs
C#
builder.Services.AddSingleton<IBreedRegistry, InMemoryBreedRegistry>();

Property-Level Async Validation With AsyncValidationAttribute

.NET 11 introduces the AsyncValidationAttribute base class. It works just like the ValidationAttribute we already know, but it gives us an IsValidAsync() method that we can override.

Let's create a KnownBreed attribute:

KnownBreedAttribute.cs
C#
using System.ComponentModel.DataAnnotations;
using Microsoft.Extensions.DependencyInjection;

public sealed class KnownBreedAttribute : AsyncValidationAttribute
{
    public KnownBreedAttribute()
    {
        ErrorMessage = "{0} is not a known breed.";
    }

    protected override async Task<ValidationResult?> IsValidAsync(
        object? value,
        ValidationContext validationContext,
        CancellationToken cancellationToken)
    {
        if (value is not string breed || string.IsNullOrWhiteSpace(breed))
        {
            return ValidationResult.Success;
        }

        var breedRegistry = validationContext.GetRequiredService<IBreedRegistry>();

        return await breedRegistry.ExistsAsync(breed, cancellationToken)
            ? ValidationResult.Success
            : new ValidationResult(
                FormatErrorMessage(validationContext.DisplayName),
                [validationContext.MemberName!]);
    }

    protected override ValidationResult? IsValid(
        object? value,
        ValidationContext validationContext)
    {
        throw new InvalidOperationException(
            $"{nameof(KnownBreedAttribute)} only supports asynchronous validation.");
    }
}

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

We inherit from AsyncValidationAttribute and set a default ErrorMessage in the constructor. The {0} placeholder is replaced with the property's display name when we call FormatErrorMessage().

In the IsValidAsync() method, we first skip empty values. This is intentional. Checking for empty values is the job of [Required], and we don't want our attribute to report a second, confusing error for the same problem.

Next, we resolve our IBreedRegistry from the ValidationContext. The ValidationContext implements IServiceProvider, so we can use the familiar GetRequiredService<T>() extension method from the Microsoft.Extensions.DependencyInjection namespace. This is how async validators get access to databases, HTTP clients, and anything else we've registered.

Then, we pass the CancellationToken we get from the framework down to our service. Always pass the token along. Our validation now does real I/O, and we don't want it to keep running when nobody is waiting for the result anymore.

Finally, when the breed doesn't exist, we return a ValidationResult that includes the MemberName. This ties the error to the Breed property, so it appears under the correct key in the error response.

Why Does IsValid() Throw?

You probably noticed that we also override the synchronous IsValid() method and simply throw an InvalidOperationException. That looks odd at first.

AsyncValidationAttribute still inherits from ValidationAttribute, so it has to support both the synchronous and asynchronous code paths. The framework never calls both of them. It picks one based on how validation is invoked.

For Minimal APIs, the validation pipeline always uses the async path. That means our IsValid() method will never be called by our endpoints. But if somebody validates our model through a synchronous API, like the good old Validator.TryValidateObject() method, throwing makes it crystal clear that the rule can't run there. That's much better than silently letting invalid data through. This is also the approach Microsoft recommends in the official docs.

Using the Attribute

Now, we can decorate our request model:

CreateCatRequest.cs
C#
public record CreateCatRequest(
    [Required, Length(2, 25)] string Name,
    [Required, Length(2, 20), KnownBreed] string Breed,
    [Required] int AgeInMonths);

We use our new [KnownBreed] attribute right next to the built-in ones. There's nothing special about it from the model's point of view.

And our endpoint goes back to being as clean as it was in .NET 10:

Program.cs
C#
catRoutes.MapPost("", (CreateCatRequest request) =>
{
    return TypedResults.Created($"/api/cats/{Random.Shared.Next(1, 999)}", request);
});

No injected services, no validation dictionaries, and no if statements. Just business logic.

Let's send a request with a breed that doesn't exist:

curl --location 'https://localhost:7298/api/cats' \
--header 'Content-Type: application/json' \
--data '{
    "name": "Cody",
    "breed": "Orange Menace",
    "ageInMonths": 40
}'

Our API responds with a validation error:

JSON
{
    "title": "One or more validation errors occurred.",
    "errors": {
        "Breed": [
            "Breed is not a known breed."
        ]
    }
}

The error format is the same one we got from data annotations in .NET 10. Our frontend doesn't need to know or care that this rule hit a database.

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

Attributes are great for rules that look at a single value. But what if our async rule needs to look at more than one property?

Object-Level Async Validation With IAsyncValidatableObject

Let's add another rule to our API. Each cat belongs to an owner, and an owner can't have two cats with the same name. Imagine yelling "Cody!" and having two orange cats show up. This rule needs both the OwnerId and the Name properties, and it needs to query a database.

A property attribute can't reliably see other properties, so this is a job for the new IAsyncValidatableObject interface. It's the async sibling of the IValidatableObject interface we used in the .NET 10 article.

First, let's add a repository method that our rule will call:

CatRepository.cs
C#
public interface ICatRepository
{
    Task<bool> OwnerHasCatNamedAsync(
        int ownerId,
        string name,
        CancellationToken cancellationToken);
}

public sealed class InMemoryCatRepository : ICatRepository
{
    public async Task<bool> OwnerHasCatNamedAsync(
        int ownerId,
        string name,
        CancellationToken cancellationToken)
    {
        // Another small delay to simulate a database call
        await Task.Delay(50, cancellationToken);

        return ownerId == 1
            && string.Equals(name, "Cody", StringComparison.OrdinalIgnoreCase);
    }
}

In our demo, the owner with an ID of 1 already has a cat named Cody.

We register it as well:

Program.cs
C#
builder.Services.AddSingleton<ICatRepository, InMemoryCatRepository>();

Now, let's update our CreateCatRequest:

CreateCatRequest.cs
C#
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.DependencyInjection;

public record CreateCatRequest : IAsyncValidatableObject
{
	[Required, Length(2, 25)]
	public required string Name { get; init; }

	[Required, Length(2, 20), KnownBreed]
	public required string Breed { get; init; }

	[Required]
	public required int AgeInMonths { get; init; }

	[Range(1, int.MaxValue)]
	public required int OwnerId { get; init; }

	public async IAsyncEnumerable<ValidationResult> ValidateAsync(
		ValidationContext validationContext,
		[EnumeratorCancellation] CancellationToken cancellationToken = default)
	{
		var catRepository = validationContext.GetRequiredService<ICatRepository>();

		if (await catRepository.OwnerHasCatNamedAsync(OwnerId, Name, cancellationToken))
		{
			yield return new ValidationResult(
				$"Owner {OwnerId} already has a cat named {Name}.",
				[nameof(Name)]);
		}
	}

	public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
	{
		throw new InvalidOperationException(
			$"{nameof(CreateCatRequest)} only supports asynchronous validation.");
	}
}

We implement the IAsyncValidatableObject interface, which requires two methods: ValidateAsync() and the synchronous Validate(). Just like with our attribute, the synchronous method throws, because our rule can't work without I/O.

The ValidateAsync() method returns an IAsyncEnumerable<ValidationResult>. This means we can yield return as many errors as we need, one by one, just like we did with IValidatableObject.

Note the [EnumeratorCancellation] attribute on the CancellationToken parameter. It comes from the System.Runtime.CompilerServices namespace, and it makes sure the token gets flowed correctly into our async iterator. If we forget it, the compiler will warn us about it.

The same ordering rule we learned about in .NET 10 still applies here: object-level validation only runs after all property-level validation passes. This includes our async [KnownBreed] attribute. If the breed is unknown, ValidateAsync() never executes. This is actually a nice side effect, as we don't hit the database for the owner check when we already know the request is invalid.

Let's try to give owner 1 a second cat named Cody:

curl --location 'https://localhost:7298/api/cats' \
--header 'Content-Type: application/json' \
--data '{
    "name": "Cody",
    "breed": "Domestic Shorthair",
    "ageInMonths": 12,
    "ownerId": 1
}'

And we get:

JSON
{
    "title": "One or more validation errors occurred.",
    "errors": {
        "Name": [
            "Owner 1 already has a cat named Cody."
        ]
    }
}

If you've followed my previous article and customized the IProblemDetailsService to return 422 Unprocessable Entity, it keeps working without any changes. Async validation errors go through the exact same pipeline as the synchronous ones. Just make sure your customization also sets context.HttpContext.Response.StatusCode, not only context.ProblemDetails.Status. Otherwise, the JSON body says 422, but the actual HTTP status code stays 400. I've updated the original article with the fix.

Things to Watch Out For

Async validation is a great addition, but rules that do I/O come with new responsibilities. Here are the things I'd keep in mind before using it in a real application.

Async Rules Can Run in Parallel

According to the official documentation, async validation operations can run in parallel, and their execution and completion order isn't guaranteed. This means our rules must never depend on each other or on running in a specific order.

It also has a less obvious consequence. If you have several async rules that resolve the same scoped DbContext, they might end up using it at the same time. EF Core's DbContext is not thread-safe, so this can lead to exceptions. To stay on the safe side, I prefer to use the IDbContextFactory<T> interface in validators and create a short-lived context for each check.

Validation Doesn't Replace Database Constraints

Our "unique name per owner" rule checks the database before the handler runs. Between that check and the moment we actually insert the cat, another request might insert a cat with the same name. Async validation gives our users friendly error messages, but it is not a guarantee. You should still keep a unique index in your database and handle the violation in your handler.

Every Request Now Pays for I/O

With synchronous data annotations, validation is cheap. With async rules, every request that reaches the validation step makes at least one network round trip. Keep the queries simple, use indexes, and consider caching data that rarely changes, like our breed registry.

Your Types Must Be Discoverable

Validation in .NET 11 still relies on a source generator. If AddValidation() is called in a different assembly than the one declaring your request models, your rules will silently not run. There's no runtime exception and no log entry. If you split your models into a class library, make sure to call AddValidation() from that assembly too, as described in the official docs.

What About FluentValidation?

In my FluentValidation vs .NET 10 Built-In Validation: Performance Benchmark post, we saw that the built-in validation is a solid alternative to FluentValidation. But async rules were one of the strongest reasons to stick with FluentValidation, which has supported them for years through methods like MustAsync().

.NET 11 levels the playing field on that front. Here's how the two compare now:

Feature.NET 11 Built-InFluentValidation
Async property rules✅ AsyncValidationAttribute✅ MustAsync()
Async cross-property rules✅ IAsyncValidatableObject✅ MustAsync() on the root object
Runs automatically before the handler✅❌ (needs a filter or manual call)
Rules live outside the model❌✅
Extra dependencies❌✅

If you prefer keeping your validation rules separate from your models, FluentValidation is still a great choice. But if you were only using it because of async rules, .NET 11 gives you a good reason to reconsider.

Conclusion

Async validation was the missing piece of the built-in validation story for Minimal APIs. With AsyncValidationAttribute and IAsyncValidatableObject, we can now move database-backed rules out of our handlers and back into our models, where they belong.

Our handlers stay clean, all validation errors come back in the same consistent format, and invalid requests never reach our business logic, even when finding out that they're invalid requires a trip to the database.

Frequently Asked Questions

Do I need to install a NuGet package for async validation?

No. If your project targets net11.0 and uses the Web SDK, everything you need is part of the ASP.NET Core shared framework. You only need the Microsoft.Extensions.Validation NuGet package for plain class libraries that declare validatable types.

Do I have to implement the synchronous IsValid() or Validate() methods?

Yes, they're required. Minimal APIs never call them, so if your rule can't work synchronously, throw an InvalidOperationException from them.

Can I mix synchronous and asynchronous attributes on the same property?

Yes. As we saw with the Breed property, [Required], [Length] and our async [KnownBreed] attribute work together without any issues.

Does ValidateAsync() run if a property attribute fails?

No. Object-level validation only runs after all property-level validation passes, both synchronous and asynchronous.

How do I access services inside an async validator?

Use the GetRequiredService<T>() or GetService<T>() methods on the ValidationContext. The services have to be registered in the DI container.

Does async validation work with Blazor?

Yes. The same Microsoft.Extensions.Validation infrastructure powers Blazor form validation, so your async rules work there as well.

> keep reading

14 min read

C# 15 Union Types in ASP.NET Core Minimal APIs

Learn how to use C# 15 union types in ASP.NET Core 11 Minimal APIs. We declare unions, use exhaustive pattern matching, accept and return them as JSON, see how they show up in OpenAPI, and compare them with closed class hierarchies.