相关疑难解决方法(0)

使用自定义验证响应和流畅的验证

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

在这里我想有一个响应模型

[{
  ErrorCode:
  ErrorField:
  ErrorMsg:
}]
Run Code Online (Sandbox Code Playgroud)

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

但是新要求要求我们为每个验证失败都具有ErrorCodes。

我的示例验证器类

public class TestModelValidator :  AbstractValidator<TestModel>{

public TestModelValidator {
   RuleFor(x=> x.Name).NotEmpty().WithErrorCode("1001");
   RuleFor(x=> x.Age).NotEmpty().WithErrorCode("1002");
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以在操作中使用类似的方法以获得验证结果

选项1:

 var validator = new TestModelValidator();
    var result = validator.Validate(inputObj);
    var errorList = result.Error;
Run Code Online (Sandbox Code Playgroud)

并将操作ValidationResult操作到我的自定义响应对象。或
Opt2:

I can use [CustomizeValidator] attribute and maybe an Interceptors.
Run Code Online (Sandbox Code Playgroud)

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

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

要求指出正确的资源。

.net c# fluentvalidation asp.net-web-api asp.net-core

7
推荐指数
4
解决办法
5086
查看次数