我處理請求的DTO的自動驗證評估FluentValidation in ServiceStack:定製響應DTO
Plugins.Add(new ValidationFeature());
container.RegisterValidators(typeof(MyValidator).Assembly);
錯誤是由序列化ErrorResponse
DTO返回給客戶端,可能是這樣的:
{
"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
}
}
UPDATE:
經過進一步挖掘到的源代碼,它看起來像,這是燒燬到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);
}
}
通過編寫定製的驗證功能我能夠達到預期的效果。但也許有更優雅的方式?
我能說什麼?奇妙!立即獲取v3.9.44 +位。 –