Asynchronous Validation With FluentValidation
How to invoke RESTful API asynchronously to validate model-property in ASP.Net Core
FluentValidation is a popular .NET library for building strongly-typed validation rules. It can be used to separate the validation logic from model classes, unlike the data annotations approach.
If you have not used FluentValidation in ASP.Net Core, I would recommend you to read the following post, before proceeding.
OK, now you know how to perform automatic basic validations in your models. However, in real-world applications, we have to implement complex validation logic as well.
In our example, we will validate a model called Applicant. While most of its properties require simple validations, there is one property called Country, which should be validated using a RESTful API. I use this endpoint for validating the country value.
I implement a country validator as follows,
Please note that CountryValidator
inherits from AsyncValidatorBase
(rather than PropertyValidator
) which handles the ShouldValidateAsync
overload.
Finally, implement ApplicantValidator
We can achieve the same validation without implementing CountryValidator
, by using a custom rule defined in ApplicantValidator
with MustAsync
.
RuleFor(m => m.Country).MustAsync(async (country, cancellation) => ( await restClient.GetAsync( $"https://restcountries.eu/rest/v2/name/{country}?fullText=true")) .IsSuccessStatusCode).WithMessage("Country name is not valid.");
It is up to you to decide which approach fits better with your design.
By the way, ASP.Net’s automatic validation does not support asynchronous validations at the moment, and it doesn’t seem to be supported in the near future either.
Therefore You’d need to disable the automatic MVC integration and invoke the validator manually from within an asynchronous controller action.
var validator = new ApplicantValidator();
var result = await validator.ValidateAsync(applicant);