asp.net Fluent验证自定义响应模型

carvr3hs  于 2023-04-08  发布在  .NET
关注(0)|答案(1)|浏览(171)

我正在使用Fluent Validation来管理www.example.com 7中的验证asp.net,它的配置如下所示,或在所有端点上自动管理。

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."
        ]
    }
}

我们怎样才能改变这个模型,使之符合我们的喜好,删除一些项目,添加一些项目呢?

1yjd4xko

1yjd4xko1#

您可以创建一个ValidationBehavior类来获取错误并重新抛出异常或将错误转换到您的模型中

public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
    where TRequest : class, IRequest<TResponse>
{
    private readonly IEnumerable<IValidator<TRequest>> _validators;
    public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators) => _validators = validators;
     public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        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(Dictionary<string, string[]> failures)
        : this()
    {
        foreach (var failure in failures)
        {
            foreach (var message in failure.Value)
            {
                Errors.Add(new ErrorDto(failure.Key, message));
            }
        }
    }
    public List<ErrorDto> Errors { get; }
}

ErrorDto类:

public class ErrorDto
{
    public ErrorDto(string propertyName, string message)
    {
        PropertyName = propertyName;
        Message = message;
    }

    public string Message { get; set; }

    public string PropertyName { get; set; }
}

更新:

您应该安装FluentValidationMediatR包。

相关问题