Validation in ASP.NET Core applications is usually straightforward when the rules involve checking required fields, string lengths, email formats, or numeric ranges. Data Annotations and validation libraries make these checks easy to implement and maintain.
However, real business applications often need to validate information that is not available inside the request model.
Consider a user registration API. Checking whether an email address has a valid format is a simple validation operation. Checking whether that email address is already registered requires a database query. Similarly, validating a product code may require calling an inventory service, while approving a payment request may require checking an external payment provider.
These operations involve I/O and should be performed asynchronously.
The challenge is that not every ASP.NET Core validation mechanism supports asynchronous execution. Developers who place database queries inside synchronous validation attributes or use asynchronous FluentValidation rules with MVC's automatic validation pipeline can encounter runtime exceptions or unexpected behavior.
ASP.NET Core and its validation libraries provide different approaches depending on the application type. The newer Microsoft.Extensions.Validation capabilities also introduce asynchronous validation support for Minimal APIs and Blazor.
This article explains how to implement asynchronous business validation, choose the right validation approach, handle cancellation, and avoid common mistakes in production applications.
Why Business Validation Needs Asynchronous Execution
Not all validation rules can be evaluated using the information already available in an HTTP request.
Consider a product creation API. The request might contain a product name, category ID, SKU, and price.
Some rules can be checked immediately:
Product name cannot be empty.
SKU must follow a specific format.
Price must be greater than zero.
Category ID must be a valid integer.
Other rules require external information:
The SKU must not already exist in the database.
The selected category must be active.
The supplier must be approved.
The product must not violate an existing business restriction.
These rules require access to a database or another service.
A synchronous implementation might look like this:
public class ProductValidator
{
private readonly AppDbContext _context;
public ProductValidator(AppDbContext context)
{
_context = context;
}
public bool IsSkuAvailable(string sku)
{
return !_context.Products.Any(x => x.Sku == sku);
}
}
This implementation performs a synchronous database operation.
If the database takes time to respond, the request thread remains occupied while waiting for the result.
An asynchronous implementation is more appropriate:
public async Task<bool> IsSkuAvailableAsync(
string sku,
CancellationToken cancellationToken)
{
return !await _context.Products.AnyAsync(
x => x.Sku == sku,
cancellationToken);
}
The asynchronous version allows the application to release the request thread while the database operation is waiting for I/O.
This does not make the database query itself faster. It helps the application use its available threads more efficiently under concurrent workloads.
Understanding the ASP.NET Core Validation Pipeline
Before implementing asynchronous validation, it is important to understand where validation happens in an ASP.NET Core application.
Traditional MVC validation is closely integrated with model binding.
When a controller receives a request model, ASP.NET Core performs model binding and validation before executing the controller action.
For example:
[HttpPost]
public IActionResult Create(
[FromBody] CreateProductRequest request)
{
if (!ModelState.IsValid)
{
return ValidationProblem(ModelState);
}
return Ok();
}
Data Annotations are automatically evaluated during this process.
The limitation is that the traditional MVC validation pipeline is synchronous. It does not provide an asynchronous execution path for validation attributes.
This creates a problem when a validation rule needs to query a database or call an external API.
Developers should not solve this by blocking asynchronous operations with methods such as .Result, .Wait(), or GetAwaiter().GetResult().
Those approaches can block request threads, reduce scalability, and introduce deadlock risks in environments with synchronization contexts.
Instead, asynchronous validation should be executed through an explicitly asynchronous application path.
The exact implementation depends on whether you are using MVC controllers, Minimal APIs, Blazor, or a validation library such as FluentValidation.
Using FluentValidation for Asynchronous Business Rules
FluentValidation provides asynchronous validation through methods such as MustAsync, CustomAsync, and WhenAsync.
This is useful when business rules require database access or external service calls.
Consider a user registration request:
public class RegisterUserRequest
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
Suppose the application must prevent duplicate email addresses.
Create a service that checks whether the email already exists:
public interface IUserService
{
Task<bool> EmailExistsAsync(
string email,
CancellationToken cancellationToken);
}
An implementation can use Entity Framework Core:
public class UserService : IUserService
{
private readonly AppDbContext _context;
public UserService(AppDbContext context)
{
_context = context;
}
public async Task<bool> EmailExistsAsync(
string email,
CancellationToken cancellationToken)
{
return await _context.Users.AnyAsync(
x => x.Email == email,
cancellationToken);
}
}
Next, create a FluentValidation validator:
using FluentValidation;
public class RegisterUserValidator
: AbstractValidator<RegisterUserRequest>
{
public RegisterUserValidator(IUserService userService)
{
RuleFor(x => x.Name)
.NotEmpty()
.MaximumLength(100);
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress()
.MustAsync(async (email, cancellationToken) =>
{
return !await userService.EmailExistsAsync(
email,
cancellationToken);
})
.WithMessage("Email address is already registered.");
}
}
The MustAsync method allows the validator to execute an asynchronous business rule.
Notice that the cancellation token is passed to the database operation. This is important because validation should not continue performing unnecessary work after the HTTP request has been cancelled.
However, defining an asynchronous validator is only part of the implementation. You must also invoke it asynchronously.
Calling ValidateAsync Instead of Validate
FluentValidation provides two main validation methods:
validator.Validate(request);
And:
await validator.ValidateAsync(request);
When a validator contains asynchronous rules, always use ValidateAsync.
Calling Validate on a validator containing MustAsync, CustomAsync, or asynchronous conditions throws an exception.
A controller can execute validation manually:
[ApiController]
[Route("api/users")]
public class UsersController : ControllerBase
{
private readonly IValidator<RegisterUserRequest> _validator;
public UsersController(
IValidator<RegisterUserRequest> validator)
{
_validator = validator;
}
[HttpPost]
public async Task<IActionResult> Register(
RegisterUserRequest request,
CancellationToken cancellationToken)
{
var result = await _validator.ValidateAsync(
request,
cancellationToken);
if (!result.IsValid)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(
error.PropertyName,
error.ErrorMessage);
}
return ValidationProblem(ModelState);
}
return Ok(new
{
Message = "User registered successfully."
});
}
}
The controller now controls when validation runs and can await asynchronous rules before executing the business operation.
This approach also makes the validation process easier to debug because the application explicitly invokes the validator.
Registering FluentValidation in ASP.NET Core
Register your validator and its dependencies through dependency injection.
For example, in Program.cs:
using FluentValidation;
using FluentValidation.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddValidatorsFromAssemblyContaining<
RegisterUserValidator>();
var app = builder.Build();
app.MapControllers();
app.Run();
The application can now inject RegisterUserValidator through IValidator.
Notice that this example does not depend on FluentValidation's legacy MVC automatic validation integration.
The recommended approach for asynchronous business rules is explicit manual validation or an asynchronous filter.
FluentValidation's older ASP.NET automatic validation integration uses the synchronous MVC validation pipeline. It is therefore unsuitable for validators containing asynchronous rules.
If you want validation to happen automatically before a controller action, an asynchronous action filter or a supported third-party asynchronous validation integration is a better option.
Understanding Asynchronous Validation in .NET 11 Minimal APIs
ASP.NET Core's validation capabilities have evolved beyond traditional MVC model validation.
With .NET 10, Microsoft introduced built-in validation support for Minimal APIs through Microsoft.Extensions.Validation.
.NET 11 extends this area with asynchronous validation support.
The newer APIs include AsyncValidationAttribute and IAsyncValidatableObject. They allow validation logic to perform asynchronous operations such as database queries and external API calls.
For Minimal APIs, the validation infrastructure executes the asynchronous validation path.
This means developers can implement asynchronous rules without manually invoking a separate validator inside every endpoint.
First, register validation services in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
builder.Services.AddScoped<IUserService, UserService>();
var app = builder.Build();
The Microsoft.Extensions.Validation package provides the validation infrastructure for supported scenarios.
Next, define a custom asynchronous validation attribute.
using System.ComponentModel.DataAnnotations;
public sealed class UniqueEmailAttribute
: AsyncValidationAttribute
{
protected override async ValueTask<bool> IsValidAsync(
object? value,
ValidationContext validationContext,
CancellationToken cancellationToken)
{
if (value is not string email ||
string.IsNullOrWhiteSpace(email))
{
return true;
}
var userService = validationContext
.GetRequiredService<IUserService>();
var exists = await userService.EmailExistsAsync(
email,
cancellationToken);
return !exists;
}
protected override ValidationResult? IsValid(
object? value,
ValidationContext validationContext)
{
throw new InvalidOperationException(
"This validation attribute requires asynchronous validation.");
}
}
The asynchronous method queries the user service and returns whether the email is available.
The synchronous method throws because this attribute is intended to run through an asynchronous validation path.
Next, apply the attribute to the request model:
using System.ComponentModel.DataAnnotations;
public class RegisterUserRequest
{
[Required]
public string Name { get; set; } = string.Empty;
[Required]
[EmailAddress]
[UniqueEmail]
public string Email { get; set; } = string.Empty;
}
Finally, use the request model in a Minimal API endpoint:
app.MapPost("/users", (
RegisterUserRequest request) =>
{
return Results.Ok(new
{
Message = "Validation completed successfully."
});
});
With validation registered, supported Minimal API request parameters are validated before the endpoint handler executes.
If validation fails, ASP.NET Core returns a 400 Bad Request response containing validation problem details.
The important difference is that Minimal APIs use the asynchronous validation path, while traditional MVC model validation remains synchronous.
Using IAsyncValidatableObject for Object-Level Rules
Sometimes a validation rule depends on multiple properties rather than a single field.
For example, an order might contain a delivery date and a shipping method. The application needs to verify whether the selected shipping method can deliver the order by the requested date.
A property-level validation attribute may not be the best place for this logic.
.NET 11 introduces IAsyncValidatableObject support through Microsoft.Extensions.Validation.
This interface allows a model to implement asynchronous object-level validation.
Consider the following example:
using System.ComponentModel.DataAnnotations;
public class CreateOrderRequest : IAsyncValidatableObject
{
public int ShippingMethodId { get; set; }
public DateTime DeliveryDate { get; set; }
public async IAsyncEnumerable<ValidationResult> ValidateAsync(
ValidationContext validationContext,
[System.Runtime.CompilerServices.EnumeratorCancellation]
CancellationToken cancellationToken = default)
{
var shippingService =
validationContext.GetRequiredService<IShippingService>();
var available = await shippingService
.CanDeliverAsync(
ShippingMethodId,
DeliveryDate,
cancellationToken);
if (!available)
{
yield return new ValidationResult(
"The selected shipping method cannot deliver on this date.",
new[] { nameof(DeliveryDate) });
}
}
public IEnumerable<ValidationResult> Validate(
ValidationContext validationContext)
{
throw new InvalidOperationException(
"Asynchronous validation is required.");
}
}
The asynchronous validation method checks the relationship between two properties and returns a validation error when the requested delivery date is unavailable.
For Minimal APIs, Microsoft.Extensions.Validation uses the asynchronous validation path.
One important detail is that asynchronous validation operations can run in parallel, and their completion order is not guaranteed.
Therefore, validation rules should not depend on one another executing in a particular sequence.
If one rule requires the result of another rule, combine those operations into a single validation operation or move the dependent logic into a dedicated business service.
Choosing Between FluentValidation and Microsoft.Extensions.Validation
Both approaches support asynchronous validation, but they solve slightly different problems.
FluentValidation is useful when an application needs a dedicated validation layer with reusable rules, conditional validation, custom validators, and complex validation composition.
Microsoft.Extensions.Validation provides built-in validation infrastructure for supported ASP.NET Core scenarios, including asynchronous validation in Minimal APIs and Blazor.
The choice depends on the application architecture.
Requirement | Recommended Approach |
|---|
Complex reusable validation rules | FluentValidation |
Asynchronous validation in Minimal APIs | Microsoft.Extensions.Validation |
Asynchronous object-level validation | IAsyncValidatableObject |
Asynchronous property-level validation | AsyncValidationAttribute |
Traditional MVC validation | Manual asynchronous validation or an asynchronous filter |
Simple required fields and string checks | Data Annotations |
These approaches can also coexist in a solution, but avoid maintaining duplicate rules in multiple validation systems.
Choose one clear location for each business rule so that the same condition is not implemented differently across controllers, endpoints, and services.
Handling Cancellation and External Service Failures
Asynchronous validation frequently depends on services outside the current application.
A database may become unavailable, an external API may time out, or a client may disconnect before validation finishes.
A production implementation should account for these situations.
Always pass the request cancellation token to database and HTTP operations.
For example:
public async Task<bool> EmailExistsAsync(
string email,
CancellationToken cancellationToken)
{
return await _context.Users.AnyAsync(
x => x.Email == email,
cancellationToken);
}
For external HTTP requests, use HttpClient's cancellation-aware methods:
var response = await _httpClient.GetAsync(
requestUri,
cancellationToken);
Do not automatically convert every infrastructure failure into a validation error.
There is an important difference between a business rule failing and the validation system being unable to check the rule.
If an email already exists, the application can return a validation error.
If the database is unavailable, the application cannot reliably determine whether the email exists. That is an infrastructure failure, not proof that the input is invalid.
Handle such failures through the application's normal exception-handling and availability strategy.
Also avoid making unnecessary external calls for obviously invalid input. Perform basic checks first, then execute the asynchronous business validation when the request is eligible.
Avoiding Race Conditions in Asynchronous Validation
One of the most important production considerations is that validation does not guarantee that a business condition remains true when the application eventually writes data.
Consider a registration endpoint that checks whether an email address already exists.
Two requests can arrive at almost the same time:
Request A checks the email address and finds no existing user.
Request B checks the same email address and also finds no existing user.
Both requests continue to the registration operation.
Both attempt to create an account using the same email address.
Even though validation succeeded for both requests, the application can still create duplicate records unless the database enforces uniqueness.
The correct solution is to use a unique database constraint.
For example, with Entity Framework Core:
protected override void OnModelCreating(
ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasIndex(x => x.Email)
.IsUnique();
}
The application should still perform the asynchronous validation to provide a useful error before attempting the insert.
However, it must also handle the database constraint violation because the database is the final authority on uniqueness.
This principle applies to inventory availability, booking systems, coupon usage, account registration, and other business rules that can change between validation and execution.
Validation improves the user experience. Database constraints and transactional operations protect data integrity.
Common Mistakes When Implementing Async Validation
Several implementation mistakes can make asynchronous validation unreliable.
Calling Validate Instead of ValidateAsync
When a FluentValidation validator contains asynchronous rules, calling Validate throws an exception.
Always use ValidateAsync and pass the request cancellation token.
Using Asynchronous Rules in MVC Automatic Validation
Traditional MVC model validation is synchronous.
FluentValidation's legacy automatic MVC validation integration cannot execute asynchronous rules correctly. Use manual validation or an asynchronous action filter instead.
Blocking Asynchronous Operations
Calling .Result or Wait on asynchronous database operations blocks threads and can reduce application scalability.
Use async and await throughout the request path.
Performing Database Operations Inside Validation Attributes Without a Supported Async Pipeline
Traditional ValidationAttribute implementations are synchronous.
For .NET 11 Minimal APIs and supported Blazor scenarios, use AsyncValidationAttribute or IAsyncValidatableObject through Microsoft.Extensions.Validation.
For MVC controllers, use an explicitly asynchronous validation approach.
Treating Infrastructure Failures as Invalid Input
A failed database query does not mean that the user's input is invalid.
Keep business validation errors separate from service failures, timeouts, and unavailable dependencies.
Depending on Validation for Data Integrity
A successful validation check does not guarantee that a database condition will remain unchanged.
Use unique constraints, transactions, and appropriate concurrency controls to protect important business rules.
Best Practices for Production ASP.NET Core Applications
A reliable asynchronous validation design starts with a clear separation between request validation and business operations.
Keep simple checks close to the request model. Use dedicated validators or validation services for rules that require external information.
Avoid putting complex database queries directly inside controller actions or custom attributes. Use injected services that can be tested independently.
Pass cancellation tokens through every asynchronous operation and avoid unnecessary external calls when basic validation has already failed.
Choose the validation mechanism based on the application type. FluentValidation with ValidateAsync is a practical option for MVC controllers, while Microsoft.Extensions.Validation provides asynchronous validation support for Minimal APIs in .NET 11.
Finally, enforce critical business constraints at the database or transactional level. An asynchronous validation result is not a substitute for data integrity controls.
Summary
Asynchronous business validation is essential for modern ASP.NET Core applications that depend on databases, external APIs, and shared business services.
FluentValidation provides MustAsync, CustomAsync, and ValidateAsync for applications that need reusable asynchronous validation rules. However, its legacy MVC automatic validation integration uses a synchronous pipeline and should not be used with asynchronous rules.
.NET 11 extends the built-in validation infrastructure through Microsoft.Extensions.Validation, AsyncValidationAttribute, and IAsyncValidatableObject. These capabilities allow Minimal APIs and supported Blazor scenarios to perform asynchronous validation without blocking the request thread.
The most important part is choosing the correct validation mechanism for your application type, passing cancellation tokens, separating business errors from infrastructure failures, and enforcing critical constraints at the database level.
When these practices are followed, asynchronous validation becomes a reliable part of the ASP.NET Core request pipeline rather than a source of unexpected runtime errors.
Join the conversation! Your thoughts help the community grow.