Hello I am trying to get custom validation response for my webApi using .NET Core.
Here I want to have response model like
[{
ErrorCode:
ErrorField:
ErrorMsg:
}]
I have a validator class and currently we just check ModalState.IsValid for validation Error and pass on the modelstate object as BadRequest.
But new requirement wants us to have ErrorCodes for each validation failure.
My sample Validator Class
public class TestModelValidator : AbstractValidator<TestModel>{
public TestModelValidator {
RuleFor(x=> x.Name).NotEmpty().WithErrorCode("1001");
RuleFor(x=> x.Age).NotEmpty().WithErrorCode("1002");
}
}
I can use something similar in my actions to get validation result
Opt1:
var validator = new TestModelValidator();
var result = validator.Validate(inputObj);
var errorList = result.Error;
and manipulate ValidationResult to my customn Response object.
or
Opt2:
I can use [CustomizeValidator] attribute and maybe an Interceptors.
but for Opt2 I don't know how to retrieve ValidationResult from interceptor to controller action.
All I want is to write a common method so that I avoid calling Opt1 in every controller action method for validation.
Request to point me to correct resource.
Refer this link for answer: https://github.com/JeremySkinner/FluentValidation/issues/548
Solution:
What I've done is that I created a basevalidator class which inherited both IValidatorInterceptor and AbstractValidator. In afterMvcvalidation method if validation is not successful, I map the error from validationResult to my custom response object and throw Custom exception which I catch in my exception handling middleware and return response.
On Serialization issue where controller gets null object:
modelstate.IsValid will be set to false when Json Deserialization fails during model binding and Error details will be stored in ModelState. [Which is what happened in my case]
Also due to this failure, Deserialization does not continue further and gets null object in controller method.
As of now, I have created a hack by setting serialization errorcontext.Handled = true manually and allowing my fluentvalidation to catch the invalid input.
https://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm [defined OnErrorAttribute in my request model].
I am searching for a better solution but for now this hack is doing the job.