The entire ValidationAttribute → GetValidationResult → IsValid chain is synchronous. The ASP.NET Core validation framework (IValidatableInfo.ValidateAsync) is async at the orchestration level (recursive traversal of object graphs), but calls attribute.GetValidationResult() synchronously at each step. There's no way to write a ValidationAttribute that performs async work (e.g., database checks, external service calls).
ValidationAttribute— abstract base:virtual bool IsValid(object?)— deprecated, backwards compatprotected virtual ValidationResult? IsValid(object?, ValidationContext)— recommended override pointGetValidationResult(object?, ValidationContext)— public entry point (callsIsValid)Validate(object?, ValidationContext)— throws on failure- Uses
_hasBaseIsValidvolatile bool for mutual-recursion override detection
Validator— static class, all sync:TryValidateObject,TryValidateProperty,TryValidateValue→ returnboolValidateObject,ValidateProperty,ValidateValue→ throw on failure- All call
attribute.GetValidationResult()internally
IValidatableObject— sync interface:IEnumerable<ValidationResult> Validate(ValidationContext)
IValidatableInfo—Task ValidateAsync(object?, ValidateContext, CancellationToken)ValidatablePropertyInfo.ValidateAsync— callsattribute.GetValidationResult()synchronously in a localValidateValue()helper (lines 153-173)ValidatableTypeInfo.ValidateAsync— callsattribute.GetValidationResult()synchronously inValidateTypeAttributes()(lines 125-150), also callsIValidatableObject.Validate()synchronouslyValidatableParameterInfo.ValidateAsync— callsattribute.GetValidationResult()synchronously (lines 86-103)- Source Generator — emits
GeneratedValidatablePropertyInfo/GeneratedValidatableTypeInfosubclasses; delegatesGetValidationAttributes()to a reflection-basedValidationAttributeCache
EditContext.Validate()— syncbool, fires syncOnValidationRequestedeventEditForm.HandleSubmitAsync()— line 204:var isValid = _editContext.Validate();with comment:// This will likely become ValidateAsync laterEditContextDataAnnotationsExtensions— callsValidator.TryValidateObject()andValidator.TryValidateProperty()synchronously. Also calls_validatorTypeInfo.ValidateAsync()but throws if it doesn't complete synchronously (line 164-166)- Architecture is prepared but blocked: async validation infrastructure exists but the sync
EventHandler<ValidationRequestedEventArgs>event model prevents true async
IModelValidator— sync interface:IEnumerable<ModelValidationResult> Validate(ModelValidationContext)DataAnnotationsModelValidator— callsAttribute.GetValidationResult(model, context)at line 83ValidationVisitor— sync recursive traversal, callsvalidators[i].Validate(context)at line 226IObjectModelValidator— sync:void Validate(ActionContext, ValidationStateDictionary?, string, object?)- Entirely synchronous — no async hooks exist
IValidateOptions<T>— sync interface:ValidateOptionsResult Validate(string?, TOptions)OptionsFactory<T>.Create()— sync, iteratesIValidateOptions<T>[]sequentiallyDataAnnotationValidateOptions<T>— callsValidator.TryValidateObject()synchronously- Options source generator — generates sync
Validate()methods ValidateOnStart/IStartupValidator— sync startup validation- Async would be a major architectural shift:
OptionsFactory.Create()is sync, lazy options resolution is sync
ValidatablePropertyInfo.cs:84— RequiredAttribute checkValidatablePropertyInfo.cs:160— General attribute validation loopValidatableTypeInfo.cs:133— Type-level attribute validationValidatableParameterInfo.cs:75— RequiredAttribute checkValidatableParameterInfo.cs:91— General attribute validation loopValidator.cs:614—TryValidate()internal helperValidator.cs:486— Required attribute check inGetObjectPropertyValidationErrorsDataAnnotationValidateOptions.cs:85— Options validation viaValidator.TryValidateObjectDataAnnotationsModelValidator.cs:83— MVC model validationValidatableObjectAdapter.cs:42— MVC IValidatableObject validationEditContextDataAnnotationsExtensions.cs:91,121— Blazor form validation
Per review feedback, the chosen approach is a new AsyncValidationAttribute class that derives from ValidationAttribute. This provides:
- Clear separation: async-only attributes are a distinct type
- Clean failure: the sync
IsValidoverride throwsNotSupportedExceptionin sync paths - No silent skipping: since it derives from
ValidationAttribute, syncValidatorstill discovers it - No sync-over-async: sync callers get a clear error telling them to use async APIs
- TODO: Add opt-in to sync-over-async (via ValidationContext and/or AppContext switch?)
- TODO: IAsyncEnumerable API to get validation results ASAP
namespace System.ComponentModel.DataAnnotations;
public abstract class AsyncValidationAttribute : ValidationAttribute
{
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
throw new NotSupportedException(
$"The validation attribute '{GetType().Name}' supports only asynchronous validation. " +
"Use the async validation APIs (e.g., Validator.TryValidateObjectAsync).");
}
// New async override point
protected abstract ValueTask<ValidationResult?> IsValidAsync(
object? value,
ValidationContext validationContext,
CancellationToken cancellationToken);
}And on the base ValidationAttribute, add the async public entry point + virtual method with default behavior:
// On ValidationAttribute itself:
// Public async entry point (counterpart to GetValidationResult)
public ValueTask<ValidationResult?> GetValidationResultAsync(
object? value,
ValidationContext validationContext,
CancellationToken cancellationToken)
{
// Calls IsValidAsync, ensures error message is populated (mirrors GetValidationResult logic)
}Key behaviors:
| Attribute Type | Sync Path (GetValidationResult) |
Async Path (GetValidationResultAsync) |
|---|---|---|
Traditional ValidationAttribute subclass (overrides IsValid) |
✅ Works normally | ✅ Default IsValidAsync delegates to sync IsValid |
AsyncValidationAttribute subclass (overrides IsValidAsync) |
❌ Throws NotSupportedException with guidance |
✅ Calls IsValidAsync |
ValidationAttribute subclass overriding both IsValid AND IsValidAsync |
✅ Uses IsValid |
✅ Uses IsValidAsync |
Same as above but without the AsyncValidationAttribute intermediate class. Users override IsValidAsync directly on ValidationAttribute and the sync IsValid base uses reflection to detect async-only attributes.
Not chosen because: Reflection-based override detection is fragile. Option C's override is cleaner and more explicit.
A completely independent attribute class.
Not chosen because: Sync Validator.TryValidateObject uses GetCustomAttributes<ValidationAttribute>() and would never see it — silent skipping (worst outcome).
An opt-in interface that ValidationAttribute subclasses can implement.
Not chosen because: Less discoverable. Users must know to implement an interface AND inherit ValidationAttribute. The subclass approach is more idiomatic for the existing DataAnnotations pattern.
Library: src/runtime/src/libraries/System.ComponentModel.Annotations/
- Add
protected virtual ValueTask<ValidationResult?> IsValidAsync(object?, ValidationContext, CancellationToken)with default calling syncIsValid(value, validationContext)wrapped inValueTask - Add
public ValueTask<ValidationResult?> GetValidationResultAsync(object?, ValidationContext, CancellationToken)mirroringGetValidationResultbut callingIsValidAsync - Use
ValueTask<>to avoid allocations when the common path is sync (default impl returnsnew ValueTask<>(syncResult))
namespace System.ComponentModel.DataAnnotations;
public abstract class AsyncValidationAttribute : ValidationAttribute
{
protected AsyncValidationAttribute() { }
protected AsyncValidationAttribute(string errorMessage) : base(errorMessage) { }
protected AsyncValidationAttribute(Func<string> errorMessageAccessor) : base(errorMessageAccessor) { }
protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
throw new NotSupportedException(
SR.Format(SR.AsyncValidationAttribute_RequiresAsync, GetType().Name));
}
// Override base IsValidAsync to make it abstract for subclasses
protected abstract override ValueTask<ValidationResult?> IsValidAsync(
object? value,
ValidationContext validationContext,
CancellationToken cancellationToken);
}Add async versions of all public validation methods:
| Existing Sync Method | New Async Method |
|---|---|
TryValidateObject(instance, ctx, results) |
TryValidateObjectAsync(instance, ctx, results, ct) |
TryValidateObject(instance, ctx, results, validateAll) |
TryValidateObjectAsync(instance, ctx, results, validateAll, ct) |
TryValidateProperty(value, ctx, results) |
TryValidatePropertyAsync(value, ctx, results, ct) |
TryValidateValue(value, ctx, results, attrs) |
TryValidateValueAsync(value, ctx, results, attrs, ct) |
ValidateObject(instance, ctx) |
ValidateObjectAsync(instance, ctx, ct) |
ValidateObject(instance, ctx, validateAll) |
ValidateObjectAsync(instance, ctx, validateAll, ct) |
ValidateProperty(value, ctx) |
ValidatePropertyAsync(value, ctx, ct) |
ValidateValue(value, ctx, attrs) |
ValidateValueAsync(value, ctx, attrs, ct) |
Internal async helpers:
GetObjectValidationErrorsAsync— async version ofGetObjectValidationErrorsGetValidationErrorsAsync— async version ofGetValidationErrorsTryValidateAsync— async version ofTryValidate, callsGetValidationResultAsync
Sync methods remain unchanged — they will throw if an AsyncValidationAttribute is encountered (via the IsValid override).
namespace System.ComponentModel.DataAnnotations;
public interface IAsyncValidatableObject : IValidatableObject
{
IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) =>
throw new NotSupportedException(
IAsyncEnumerable<ValidationResult> ValidateAsync(
ValidationContext validationContext,
CancellationToken cancellationToken = default);
}The async Validator methods will check for this interface in Step 3 of validation (after properties and type attributes), mirroring the IValidatableObject pattern.
Note: IAsyncEnumerable<> allows streaming results. The alternative Task<IEnumerable<ValidationResult>> is simpler but less flexible.
Update ref/System.ComponentModel.Annotations.cs with all new public API surface:
AsyncValidationAttributeclassIAsyncValidatableObjectinterface- All new
Validatorasync methods ValidationAttribute.IsValidAsyncandGetValidationResultAsync
Add new error message to .resx:
AsyncValidationAttribute_RequiresAsync— "The validation attribute '{0}' supports only asynchronous validation via IsValidAsync. Use Validator.TryValidateObjectAsync or the equivalent async validation API."
Library: src/aspnetcore/src/Validation/src/
These classes already have async Task ValidateAsync(...) methods. The change is to call GetValidationResultAsync instead of GetValidationResult within them.
- Line 84: Change
_requiredAttribute.GetValidationResult(...)toawait _requiredAttribute.GetValidationResultAsync(..., cancellationToken). Built-inRequiredAttributeis sync, so this completes synchronously viaValueTask. - Lines 153-173: Convert the
ValidateValuelocal function to an async method. Changeattribute.GetValidationResult(val, context.ValidationContext)toawait attribute.GetValidationResultAsync(val, context.ValidationContext, cancellationToken).
ValidateTypeAttributes(lines 125-150): Rename toValidateTypeAttributesAsync, make async, callawait attribute.GetValidationResultAsync(...)at line 133.ValidateValidatableObjectInterface(lines 152-190): Rename toValidateValidatableObjectAsync. AddIAsyncValidatableObjectsupport: whenvalue is IAsyncValidatableObject asyncValidatable, useawait foreach (var result in asyncValidatable.ValidateAsync(...)). Continue supporting existingIValidatableObjectas fallback.ValidateAsync(lines 51-105): Update to call the renamed async methods.
- Line 75: Change RequiredAttribute check to use
await _requiredAttribute.GetValidationResultAsync(..., cancellationToken) - Lines 86-103: Change attribute validation loop to use
await attribute.GetValidationResultAsync(..., cancellationToken)
Library: src/aspnetcore/src/Components/
Blazor has architecture partially prepared for async validation. Key changes:
- Add
public async Task<bool> ValidateAsync()method — async counterpart toValidate() - Add
public event Func<object, ValidationRequestedEventArgs, Task>? OnAsyncValidationRequested;— async event for validation handlers ValidateAsync()invokes async handlers, then checks!GetValidationMessages().Any()
- Line 204: Change
var isValid = _editContext.Validate()tovar isValid = await _editContext.ValidateAsync()(the existing comment says// This will likely become ValidateAsync later)
TryValidateTypeInfo(lines 147-194): Remove thethrow new InvalidOperationException("Async validation is not supported")guard at line 166. Instead, properlyawaitthevalidationTask.- Subscribe to
OnAsyncValidationRequestedinstead ofOnValidationRequestedfor the type-info validation path OnFieldChangedhandler (lines 79-102): Add async field validation usingValidator.TryValidatePropertyAsync()
Library: src/aspnetcore/src/Mvc/
MVC model validation is entirely synchronous. Full async support would require:
IModelValidator— addValueTask<IEnumerable<ModelValidationResult>> ValidateAsync(ModelValidationContext, CancellationToken)DataAnnotationsModelValidator— implement async variant callingGetValidationResultAsyncValidationVisitor— makeValidateNode()asyncIObjectModelValidator— add asyncValidateAsync()methodsValidatableObjectAdapter— supportIAsyncValidatableObject
This is a large change with broad impact across the MVC pipeline. Recommend deferring to a follow-up effort. In the interim:
- MVC
DataAnnotationsModelValidatorcallsGetValidationResult()synchronously - If an
AsyncValidationAttributeis used on an MVC model,GetValidationResult→IsValid→ throwsNotSupportedExceptionwith clear message - This is the desired behavior: users get a clear error saying MVC doesn't support async validation yet
Library: src/runtime/src/libraries/Microsoft.Extensions.Options/
Options validation is synchronous by design (fail-fast at option creation time). Full async support would require:
- New
IAsyncValidateOptions<T>interface OptionsFactory<T>— addCreateAsync()or makeCreate()async-awareDataAnnotationValidateOptions<T>— useValidator.TryValidateObjectAsync- Options source generator — generate async
ValidateAsync()methods IStartupValidator/ValidateOnStart— async startup validation
This is a major architectural shift. The sync OptionsFactory.Create() is deeply embedded in the options pattern. Recommend deferring to a follow-up effort. In the interim:
DataAnnotationValidateOptions<T>callsValidator.TryValidateObject()synchronously- If an
AsyncValidationAttributeis used on an options class, it throwsNotSupportedExceptionwith clear message - This is acceptable: options validation typically doesn't need I/O
- The generated
GeneratedValidatablePropertyInfoandGeneratedValidatableTypeInfoinherit from the base classes and only overrideGetValidationAttributes(). - The
ValidateAsyncmethods are inherited from base classes, which we're updating in Phase 2. - No emitter changes should be needed. Verify that no generated code directly calls
GetValidationResult.
- Currently emits sync
Validate()methods callingValidator.TryValidateValue() - No changes in this effort — deferred with Options async support (Phase 5)
- Test that
AsyncValidationAttributesubclass throwsNotSupportedExceptionwhen syncGetValidationResultis called - Test that
AsyncValidationAttributesubclass works viaGetValidationResultAsync - Test that traditional
ValidationAttributeworks in both sync and async paths - Test
Validator.TryValidateObjectAsyncwith mixed sync/async attributes - Test
Validator.ValidateObjectAsyncthrowsValidationExceptioncorrectly - Test
IAsyncValidatableObjectintegration in asyncValidatormethods - Test that
ValueTaskreturns synchronously for sync-only attributes (no allocation)
- Update existing
ValidatableTypeInfoTests,ValidatableParameterInfoTests - Add tests with custom
AsyncValidationAttributesubclasses working end-to-end - Test that
ValidatablePropertyInfo.ValidateAsyncproperly awaits async attributes
- Test
EditContext.ValidateAsync()with async validation attributes - Test that
EditFormproperly awaits async validation - Test field-level async validation
Using ValueTask<ValidationResult?> for IsValidAsync/GetValidationResultAsync because:
- The common case is sync attributes where default
IsValidAsyncreturnsnew ValueTask<>(syncResult)with zero allocation AsyncValidationAttributesubclasses benefit fromValueTaskpooling- Aligns with modern BCL async patterns
- Traditional
ValidationAttribute: sync path works normally (unchanged) AsyncValidationAttribute: sync path throwsNotSupportedExceptionwith clear message pointing to async API (viaIsValidoverride)- Never silently skip async validation
- Never do sync-over-async
Allows streaming results and is aligned with the pattern where validation may involve multiple async checks. If deemed too complex for V1, Task<IEnumerable<ValidationResult>> is an acceptable simplification.
- Non-breaking for existing attributes: Default
IsValidAsynconValidationAttributedelegates to sync, so all existing subclasses work in both sync and async paths - Non-breaking for existing sync callers:
Validator.TryValidateObjectetc. unchanged for sync attributes - Intentionally breaking: Using
AsyncValidationAttributewith syncValidatorthrowsNotSupportedException— this is by design, not a bug - Binary compatible: All changes are additive (new virtual method, new class, new interfaces, new static methods)
- Phase 1-2 (Core + Minimal APIs): The minimum viable async validation story. This alone enables async validation in the new Minimal API validation framework.
- Phase 3 (Blazor): High value — Blazor forms are a natural fit for async validation (UI-driven, already async). Architecture already partially prepared (existing
ValidateAsynccomment, throw-if-async guard). - Phase 4-5 (MVC + Options): Lower priority, larger scope. Defer to follow-up. Both throw clearly when async-only attributes are used.
| File | Change |
|---|---|
.../DataAnnotations/ValidationAttribute.cs |
Add IsValidAsync, GetValidationResultAsync |
.../DataAnnotations/AsyncValidationAttribute.cs |
New file — overridden sync + abstract async |
.../DataAnnotations/Validator.cs |
Add all async method counterparts |
.../DataAnnotations/IAsyncValidatableObject.cs |
New file |
ref/System.ComponentModel.Annotations.cs |
Add public API surface |
.../tests/.../ValidationAttributeTests.cs |
Async tests |
.../tests/.../ValidatorTests.cs |
Async tests |
| SR strings / .resx | New error messages |
| File | Change |
|---|---|
.../Validation/src/ValidatablePropertyInfo.cs |
Call GetValidationResultAsync |
.../Validation/src/ValidatableTypeInfo.cs |
Async type attrs, IAsyncValidatableObject support |
.../Validation/src/ValidatableParameterInfo.cs |
Call GetValidationResultAsync |
.../Validation/test/.../ValidatableTypeInfoTests.cs |
Async test updates |
.../Validation/test/.../ValidatableParameterInfoTests.cs |
Async test updates |
| File | Change |
|---|---|
.../Components/Forms/src/EditContext.cs |
Add ValidateAsync(), async event |
.../Components/Web/src/Forms/EditForm.cs |
Use ValidateAsync() |
.../Components/Forms/src/EditContextDataAnnotationsExtensions.cs |
Remove async throw guard, await properly |
| File | Reason |
|---|---|
| ASP.NET Core Validation source generator emitter | Generated classes inherit from base; no direct GetValidationResult calls |
MVC DataAnnotationsModelValidator, ValidationVisitor, etc. |
Deferred to follow-up; throws clearly if async attr used |
Options DataAnnotationValidateOptions, OptionsFactory, etc. |
Deferred to follow-up; throws clearly if async attr used |
| Options source generator | Deferred with Options async support |
Great write-up, @halter73. Just a few notes:
AsyncValidationAttribute_RequiresAsyncis good; it could be altered to not be specific toTryValidateObject(Async)and instead reference all of the-Asyncalternatives.ValidationAttribute.cs— Add Async Methods to Base ClassAsyncValidationAttributeOne other thing we could try to work into .NET 11 while we're working on this: