abp
abp copied to clipboard
Volo.Abp.FluentValidation Package seems to not be working
Is there an existing issue for this?
- [X] I have searched the existing issues
Description
I am currently trying to use the Volo.Abp.FluentValidation package following what is outlined in the documentation here.
Currently it seems that anything I define in my validator classes is not being picked up.
Reproduction Steps
I have created a sample project showcasing this not working here:
I used the started template, added one model and an appservice to showcase this behavior. I have also added API versioning as that is a requirement that I need to have working with this.
Expected behavior
FluentValidation package to detect any class using/inheriting from AbstractValidator<> and correctly triggering the rules defined.
Actual behavior
I have defined the following for My CreateBookDto Validation:
public class CreateBookValidator : AbstractValidator<CreateBookDto>
{
public CreateBookValidator()
{
RuleFor(o => o.Name).NotNull().WithMessage("TEst");
RuleFor(o => o.Price).NotEmpty();
RuleFor(o => o.AuthorId).NotEmpty();
}
}
So I expect to get validation errors for all of the properties here when I try creating a new Book. Instead I receive the following:
I don't receive errors about the missing properties and even the message for the name field is wrong. This indicates that FluentValidations are not triggering.
Regression?
No response
Known Workarounds
No response
Version
8.1.3
User Interface
Common (Default)
Database Provider
EF Core (Default)
Tiered or separate authentication server
Tiered
Operation System
Windows (Default)
Other information
No response
This is because you are using the conventional controllers.
ABP uses interceptors for parameter validation, but does not intercept controllers for performance.
https://github.com/abpframework/abp/blob/4f282552fd89d5b612e53c82ae07e29a2cd8d0c5/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcModule.cs#L221-L223 https://github.com/abpframework/abp/blob/4f282552fd89d5b612e53c82ae07e29a2cd8d0c5/framework/src/Volo.Abp.Validation/Volo/Abp/Validation/ValidationInterceptorRegistrar.cs#L19
In order to use FluentValidation, you can't use a convention controller, you need to create one manually.
For example: https://github.com/abpframework/abp/blob/4f282552fd89d5b612e53c82ae07e29a2cd8d0c5/modules/identity/src/Volo.Abp.Identity.HttpApi/Volo/Abp/Identity/IdentityRoleController.cs#L14
And please make the repo private
You can add an ActionFilter to validate the model using FluentValidate.
https://github.com/JadynWong/AbpIssue/commit/eec5290d5c1ac20c0ae7abedb2141fade058e61b#diff-e7c9195c610944a0f739a7bca415e73d593bdd5712205d1b8322af4aedb8e0dd
Refer https://github.com/SharpGrip/FluentValidation.AutoValidation
Only basic tests were performed. It would be better if abp could provide built-in support.
This solution seems to be working for now, thank you @JadynWong