c# - Use custom validation responses with fluent validation -
hello trying custom validation response webapi using .net core.
here want have response model
[{ errorcode: errorfield: errormsg: }]
i have validator class , check modalstate.isvalid validation error , pass on modelstate object badrequest.
but new requirement wants have errorcodes 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 similar in actions validation result
opt1:
var validator = new testmodelvalidator(); var result = validator.validate(inputobj); var errorlist = result.error;
and manipulate validationresult customn response object. or
opt2:
i can use [customizevalidator] attribute , maybe interceptors.
but opt2 don't know how retrieve validationresult interceptor controller action.
all want write common method avoid calling opt1 in every controller action method validation.
request point me correct resource.
refer link answer: https://github.com/jeremyskinner/fluentvalidation/issues/548
solution:
what done created basevalidator class inherited both ivalidatorinterceptor , abstractvalidator. in aftermvcvalidation method if validation not successful, mapped error validationresult custom response object , throw custom exception.
which catch in exception handling middleware , return response.
on serialization issue controller gets null object:
i see modelstate.isvalid set false when json deserialization fails during model binding , error details stored in modelstate. [which happening me]
also due failure deserialization stops continue further , null object in controller method.
currently have given hack setting serialization errorcontext.handled = true manually , allowing fluentvalidation catch invalid input.
https://www.newtonsoft.com/json/help/html/serializationerrorhandling.htm [defined onerrorattribute in request model].
i searching better solution hack doing job..
Comments
Post a Comment