How to invoke RESTfFUL API asynchronously to validatemodel-property in ASP.Net Core
Fluent Validation is apopular .NET library for building strongly-typed validation rules. It can beused to separate the validation logic from model classes, unlike the dataannotations approach.
If you have not usedFluentValidation in ASP.Net Core, I would recommend you read this post,before proceeding.
Now you know how toperform automatic basic validations in your models. However, in real-worldapplications, we have to implement complex validation logic as well.
In our example, we willvalidate a model called Applicant. While most of its properties require simplevalidations, there is one property called Country, which should be validatedusing a RESTful API. I use this endpoint for validating the country value.
view rawApplicant.cs hosted with❤ by GitHub
I implement a countryvalidator as below;
view rawCountryValidator.cs hosted with ❤ by GitHub
Please note that CountryValidatorinherits from AsyncValidatorBase (rather than PropertyValidator ) which handles the ShouldValidateAsync overload.
Finally, implement ApplicantValidator
view rawApplicantValidator.cs hosted with ❤ by GitHub
We can achieve the samevalidation without implementing CountryValidator, byusing a custom rule defined in ApplicantValidator with MustAsync.
RuleFor(m =>m.Country).MustAsync(async (country, cancellation) => (
.IsSuccessStatusCode).WithMessage("Country name isnot valid.");
It is up to you todecide which approach fits better with your design. ASP.Net’s automaticvalidation does not support asynchronous validations at the moment, and itdoesn’t seem to be supported in the near future either.
Therefore you’d need todisable the automatic MVC integration and invoke the validator manually fromwithin an asynchronous controller action.
var validator = newApplicantValidator();
var result = awaitvalidator.ValidateAsync(applicant);
Try it out yourself!
Further Reading - https://github.com/FluentValidation/FluentValidation/issues/413