Aspnetcore: Async Model Validation

Created on 14 Feb 2019  路  4Comments  路  Source: dotnet/aspnetcore

Is your feature request related to a problem? Please describe.

Model validation is synchronous, but if there's a database call or other awaitable call, it would be nice to have an async option.

See https://github.com/aspnet/Mvc/issues/786.

Describe the solution you'd like

Add virtual methods for ValidationAttribute:

Task<bool> IsValidAsync(object value);
Task<ValidationResult> IsValidAsync(object value, ValidationContext validationContext);

Describe alternatives you've considered

Currently working around by using synchronous DB calls.

area-mvc

Most helpful comment

I second this featue Request, but not for the ValidationAttribute (because there is no direct DI for the Attribute and accessing a DbContext needs scoped services).

I have to lookup in the database, and would like to not look the thread ;)

For my perspective with the IAsyncEnumerable of C# 8 i should be possible to create an IAsyncModelValidator.

  public interface IAsyncModelValidator
  {
    IAsyncEnumerable<ModelValidationResult> ValidateAsync(ModelValidationContext context);
  }

All 4 comments

I second this featue Request, but not for the ValidationAttribute (because there is no direct DI for the Attribute and accessing a DbContext needs scoped services).

I have to lookup in the database, and would like to not look the thread ;)

For my perspective with the IAsyncEnumerable of C# 8 i should be possible to create an IAsyncModelValidator.

  public interface IAsyncModelValidator
  {
    IAsyncEnumerable<ModelValidationResult> ValidateAsync(ModelValidationContext context);
  }

Currently we use ValidationAttribute for validating commands (if the id of the command already exist in database for instance). Since the IsValid metods are synchronous we are seeing thread pool starvation under high load, since the call chain to db is blocked. So this feature would be highly appreciated.

Our temporary "work around" is to explicitly set the ThreadPool min size, which seem to work. Such as:

var threadCount = 1000;
ThreadPool.GetMaxThreads(out _, out var completionThreads);
ThreadPool.SetMinThreads(threadCount, completionThreads);

Someone "solved" it in another fashion?

1- just synchronous validation
2- if errors in one in 1 then skip 3
3- asynchronous validations

Thanks for contacting us, @bradlis7.
This is not something we plan to do in the near future.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

markrendle picture markrendle  路  3Comments

ermithun picture ermithun  路  3Comments

Pixel-Lord picture Pixel-Lord  路  3Comments

ipinak picture ipinak  路  3Comments

Kevenvz picture Kevenvz  路  3Comments