我正在评估ServiceStack 中的 FluentValidation以处理请求 DTO 的自动验证:
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(MyValidator).Assembly);
通过序列化 DTO 将错误返回给客户端ErrorResponse
,可能如下所示:
{
"ErrorCode": "GreaterThan",
"Message": "'Age' must be greater than '0'.",
"Errors": [
{
"ErrorCode": "GreaterThan",
"FieldName": "Age",
"Message": "'Age' must be greater than '0'."
},
{
"ErrorCode": "NotEmpty",
"FieldName": "Company",
"Message": "'Company' should not be empty."
}
]
}
我想知道是否可以使用不同的响应 DTO 返回错误。例如:
{
"code": "123",
"error": "'Age' must be greater than '0'."
}
我知道可以在服务中明确使用验证器:
public MyService : Service
{
private readonly IValidator<MyRequestDto> validator;
public MyService(IValidator<MyRequestDto> validator)
{
this.validator = validator;
}
public object Get(MyRequestDto request)
{
var result = this.validator.Validate(request);
if (!result.IsValid)
{
throw new SomeCustomException(result);
}
... at this stage request DTO validation has passed
}
}
但这里的问题是是否有可能在某处隐式拦截此验证错误,以便我可以替换响应 DTO 并获得更清洁的服务:
public MyService : Service
{
public object Get(MyRequestDto request)
{
... at this stage request DTO validation has passed
}
}
更新:
在进一步深入研究源代码后,它看起来像是被烧入了ValidationFeature
它所注册的请求过滤器,更具体地说是它注册的请求过滤器:
public class ValidationFilters
{
public void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
{
var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
if (validator == null) return;
var validatorWithHttpRequest = validator as IRequiresHttpRequest;
if (validatorWithHttpRequest != null)
validatorWithHttpRequest.HttpRequest = req;
var ruleSet = req.HttpMethod;
var validationResult = validator.Validate(
new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));
if (validationResult.IsValid) return;
var errorResponse = DtoUtils.CreateErrorResponse(
requestDto, validationResult.ToErrorResult());
res.WriteToResponse(req, errorResponse);
}
}
通过编写自定义验证功能,我能够达到预期的效果。但也许有更优雅的方式?