我正在使用 Fluent Validation 来管理 asp.net 7 中的验证,其配置如下或跨所有端点自动管理。
builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddValidatorsFromAssemblyContaining<RegisterViewModelValidator>();
如果我的模型有错误,API输出如下
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-fc0a67254820e5cebc9607058a4e1229-b9617612ef2a4d7c-00",
"errors": {
"UserName": [
"The length of 'User Name' must be at least 5 characters. You entered 4 characters."
]
}
}
我们如何根据自己的喜好更改此模型并删除一些项目并添加一些项目?
您可以创建一个
ValidationBehavior
类来获取错误并重新抛出异常或将错误转换为您的模型
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : class, ICommand<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) => _validators = validators;
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
if (!_validators.Any())
{
return await next();
}
var context = new ValidationContext<TRequest>(request);
var errorsDictionary = _validators
.Select(x => x.Validate(context))
.SelectMany(x => x.Errors)
.Where(x => x != null)
.GroupBy(
x => x.PropertyName,
x => x.ErrorMessage,
(propertyName, errorMessages) => new
{
Key = propertyName,
Values = errorMessages.Distinct().ToArray()
})
.ToDictionary(x => x.Key, x => x.Values);
if (errorsDictionary.Any())
{
throw new CustomValidationException(errorsDictionary);
// throw new Exception();
}
return await next();
}
}
CustomValidationException
班级:
public class CustomValidationException : Exception
{
public CustomValidationException()
: base("Custom validation exception have occurred.")
{
Errors = new List<ErrorDto>();
}
public CustomValidationException(IEnumerable<ValidationFailure> failures)
: this()
{
foreach (var failure in failures)
{
var error = new ErrorDto(failure.ErrorCode,
failure.ErrorMessage,
failure.PropertyName);
Errors.Add(error);
}
}
public List<ErrorDto> Errors { get; }
}
ErrorDto
班级:
public class ErrorDto
{
public ErrorDto(string code, string message, string propertyName)
{
PropertyName = propertyName;
Code = code;
Message = message;
}
public string Code { get; set; }
public string Message { get; set; }
public string PropertyName { get; set; }
}