Skip to content

Implementing async validation logic should not require implementing sync IsValid #131498

Closed

Description

@danroth27

To write an async validation rule — say a uniqueness check against a database — an author derives from AsyncValidationAttribute and implements IsValidAsync. But IsValid(object?, ValidationContext) is also abstract, so they must implement a synchronous method too:

error CS0534: 'UniqueUsernameAttribute' does not implement inherited abstract member
'AsyncValidationAttribute.IsValid(object?, ValidationContext)'

That method is usually irrelevant to what the author is trying to express. Their rule needs I/O; there's nothing meaningful for the sync overload to do. So it becomes a required stub whose correct contents aren't obvious.

The choice is confusing and error-prone

How should a user implement IsValid, and why does AsyncValidationAttribute require it at all? AsyncValidationAttribute is for defining async validation logic; for sync logic there is already ValidationAttribute. It derives from ValidationAttribute so that it can influence what happens when only the synchronous validation path is called. The framework's own validators could detect that case and offer configurable behavior, but these attributes may also be consumed by validation systems the framework doesn't control — attribute.IsValid(...) and attribute.GetValidationResult(...) are public entry points that bypass Validator entirely, so the behavior has to live on the attribute itself.

This is not a rare path. Existing DataAnnotations-based validation systems are synchronous only; asynchronous validation is new in .NET 11 and opt-in. So whatever an author writes in IsValid is what essentially every existing consumer of that attribute will execute today. The synchronous overload is the common case at the moment, not the fallback.

In most cases the right behavior is to throw. Running sync-only validation when async validation is required is a programming error, and the alternatives are both worse:

  • Silently passing means the rule doesn't run at all, which is a security risk.
  • Failing is also wrong, because there is no reasonable message to show the user — they have no control over whether validation was invoked synchronously or asynchronously.

This does mean a system running synchronous validation will hit an exception when handed a newer type that requires async validation. That is the correct outcome: running sync validation on a type that requires async validation is invalid, and silently ignoring the validation logic would be a security risk. It is also worth noting that leaving IsValid to the author does not avoid this — it only makes the result unpredictable. Since existing systems are sync-only, they are the ones that will execute whatever each author wrote, so the behavior they see is currently outside the framework's control.

Requiring users to implement IsValid themselves pushes them toward two bad shapes:

  • Sync-over-async. Users will try to implement IsValid in terms of the async logic. This may work in limited cases, but in environments like ASP.NET Core it can cause thread pool starvation.
  • Returning success. Users may assume both sync and async validation always run, and implement IsValid to always return valid. I've seen AI coding assistants make exactly this assumption.

The same applies to IAsyncValidatableObject

IAsyncValidatableObject derives from IValidatableObject and declares only ValidateAsync, so implementing async object-level validation likewise requires supplying a synchronous Validate with the same unhelpful choice of contents.

Proposal

Make AsyncValidationAttribute.IsValid virtual, with a default implementation that throws to indicate synchronous validation isn't supported for the attribute. Give IAsyncValidatableObject.Validate an equivalent default interface implementation.

  • Authors writing async validation implement only the async member.
  • Authors who have a correct synchronous equivalent can still override it.
  • Existing sync-only validation systems get one predictable behavior instead of whatever each author happened to write.

Related

This issue is about the authoring requirement only, not whether a synchronous contract should exist.

Observed on 11.0.0-preview.6.26359.118.

Activity

  1. added
    untriaged
    on Jul 28, 2026
  2. dotnet-policy-service commented on Jul 28, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-componentmodel-dataannotations
    See info in area-owners.md if you want to be subscribed.

  3. MihuBot commented on Jul 28, 2026

    @MihuBot

    I'm a bot. Here is a possible related and/or duplicate issue (I may be wrong):

  4. danroth27 commented on Jul 29, 2026

    @danroth27
    MemberAuthor

    Admittedly, it does feel unnatural to implement these sync validation abstractions by throwing. It's a bit of a hack attempting to protect 3rd party validation systems that might cause more harm than good. So while this goes beyond the authoring question I scoped the issue to, it might be worth considering whether this pattern is really worth it. We could instead introduce the async abstractions without deriving from the sync ones, and then update our validators to look for the async abstractions explicitly and to throw when async rules are present but validation was invoked synchronously. That would avoid the "what do I put here?" question entirely, and would also make it clear that async validation is not supported in a sync context. This wouldn't help other validation systems that use these abstractions, but they always have the option to add similar logic to support the new async validation abstractions if they choose to.

    Worth deciding one way or the other soon: #130719 (api-approved) is already extending this pattern to options validation with IAsyncValidateOptions<T> : IValidateOptions<T> and IAsyncStartupValidator : IStartupValidator, so whatever we settle on here will be harder to change once that lands.

  5. added
    documentation
    and removed
    untriaged
    on Aug 16, 2026
  6. added this to the 11.0.0 milestone on Aug 16, 2026
  7. jeffhandley commented on Sep 9, 2026

    @jeffhandley
    Member

    We still need to follow up with documentation to provide guidance around:

    1. When to throw
    2. When to produce a validation error
    3. When it might be appropriate to have sync validation succeed as a no-op
    4. Never trying to do sync-over-async

    Turning this into a documentation issue for .NET 11.

  8. ViveliDuCh commented on Sep 25, 2026

    @ViveliDuCh
    Member

    @danroth27 @jeffhandley I propose the following guidance for the four cases in your comment, covering AsyncValidationAttribute.IsValid and the inherited IValidatableObject.Validate implementation:

    1. Throw when synchronous invocation is unsupported.
    If correctly evaluating the rule requires asynchronous work and no suitable synchronous implementation exists, throw InvalidOperationException with a message directing the developer to asynchronous validation. This represents an unsupported use of the validator, not evidence that the input is invalid.

    2. Produce a validation error when a synchronous check establishes that the input is invalid.
    Return a failed ValidationResult, or yield validation results from IValidatableObject.Validate, when the input violates a rule that can genuinely be evaluated synchronously. A local check can establish failure without performing further asynchronous work. However, passing local checks does not establish success when required asynchronous checks remain outstanding.

    3. Treat success as a no-op as an exceptional, explicitly documented choice.
    A rule that does not apply to the supplied value can legitimately return success; that is different from skipping an applicable rule. For an applicable rule requiring asynchronous validation, a deliberate synchronous no-op should be restricted to controlled orchestration where the synchronous pass is explicitly incomplete and full asynchronous validation is guaranteed before the value is accepted, persisted, published, or otherwise relied upon.

    This should not be the default for reusable validators, which cannot assume that every consumer follows that orchestration. Registering or implementing asynchronous validation alone does not establish the guarantee.

    4. Never implement the synchronous method using sync-over-async.
    Do not block on the asynchronous implementation using .Result, .Wait(), .GetAwaiter().GetResult(), or Task.Run followed by blocking. Use a genuinely synchronous implementation, reject unsupported synchronous invocation, or change the caller to await asynchronous validation.

    A key dispatch clarification: the framework does not automatically execute both implementations of the same async-capable rule. Asynchronous dispatch selects its asynchronous implementation instead of its synchronous implementation. Required shared checks must therefore also be included in the async implementation, typically through shared helpers. This does not prevent the async pipeline from executing other synchronous-only rules.

    Options implication: ValidateOnStart() is not sufficient justification for a no-op DataAnnotations fallback. Startup validation can use the async path, but synchronous creation, snapshots, and monitor reload have separate behavior. The guidance should not imply that those paths necessarily receive subsequent async validation.

    The central distinction is invalid input versus unsupported invocation versus intentionally incomplete validation. In particular, returning success must not silently turn “this rule was not evaluated” into “this value has been fully validated.”

  9. danroth27 commented on Sep 26, 2026

    @danroth27
    MemberAuthor

    @ViveliDuCh I think 1, 2, and 4 make sense and sound reasonable. I find 3 confusing and somewhat artificial - do we actually have concrete scenarios matching this exceptional situation?

  10. ViveliDuCh commented on Sep 26, 2026

    @ViveliDuCh
    Member

    do we actually have concrete scenarios matching this exceptional situation?

    @danroth27 I don't currently have a concrete end-to-end consumer that requires this exception. I was just describing a possible compatibility arrangement @jeffhandley mentioned before: synchronous UI checks followed by a mandatory async submission check, rather than an established .NET 11 framework scenario.
    I also had in mind something similar to Options name-scoped validation, where a rule is intentionally applicable only to a specific named configuration and effectively becomes a no-op for others.

    However, if we don't think this is a realistic enough scenario to justify the guidance, I'd be fine dropping it. I'd suggest simplifying point 3: returning success because a rule does not apply is legitimate, but do not return success merely because an applicable, required rule cannot run synchronously. We can revisit application-specific partial-validation guidance if a concrete scenario warrants it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-System.ComponentModel.DataAnnotationsdocumentation

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions