结合使用自定义验证响应和流畅的验证 [英] Use custom validation responses with fluent validation

查看:125
本文介绍了结合使用自定义验证响应和流畅的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用.NET Core获得针对我的webApi的自定义验证响应.

Hello I am trying to get custom validation response for my webApi using .NET Core.

在这里我想拥有

[{
  ErrorCode:
  ErrorField:
  ErrorMsg:
}]

我有一个验证器类,目前我们只检查ModalState.IsValid验证错误,然后将模型状态对象作为BadRequest传递.

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.

我的示例验证器类

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;

并将操纵ValidationResult操作到我的定制Response对象. 或
Opt2:

and manipulate ValidationResult to my customn Response object. or
Opt2:

I can use [CustomizeValidator] attribute and maybe an Interceptors.

但是对于Opt2,我不知道如何从拦截器到控制器动作中检索ValidationResult.

but for Opt2 I don't know how to retrieve ValidationResult from interceptor to controller action.

我只想编写一个通用方法,以便避免在每个控制器操作方法中调用Opt1进行验证.

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.

推荐答案

请参考此链接以获取答案: https://github.com/JeremySkinner/FluentValidation/issues/548

Refer this link for answer: https://github.com/JeremySkinner/FluentValidation/issues/548

解决方案:

我所做的是创建了一个继承了IValidatorInterceptor和AbstractValidator的basevalidator类.在afterMvcvalidation方法中,如果验证不成功,我会将错误从validateResult映射到我的自定义响应对象,并抛出自定义异常,该异常会在我的异常处理中间件中捕获并返回响应.

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.

关于控制器获取空对象的序列化问题:

modelstate.IsValid将设置为false,并且错误详细信息将存储在ModelState中. [我的情况是什么]

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.

到目前为止,我已经通过手动设置序列化errorcontext.Handled = true并允许我的fluentvalidation捕获无效输入来创建黑客.

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 [在我的请求模型中定义了OnErrorAttribute].

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.

这篇关于结合使用自定义验证响应和流畅的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆