我创建了一个验证行为,但这不会在视图中向用户显示错误。相反,它在Visual Studio中抛出一个验证异常。如何在视图中向用户显示错误?
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
var context = new ValidationContext<TRequest>(request);
var failures = _validators
.Select(x => x.Validate(context))
.SelectMany(x => x.Errors)
.Where(x=>x !=null)
.ToList();
if (failures.Any())
{
throw new ValidationException(failures);
}
return next();
}
}
public class SaveXValidator : AbstractValidator<SaveXCommand>
{
public SaveXValidator()
{
RuleFor(x=>x.ImageUrl).NotEmpty().WithMessage("Can't be empty!");
RuleFor(b => b.StartDate)
.LessThan(p => p.CreatedDate).WithMessage("error example");
}
}
您可以在视图中使用此选项在一个位置显示所有验证
<div asp-validation-summary="All" class="alert alert-danger" role="alert">
如果要在每个属性的特定点显示验证错误,可以使用此选项。
<span asp-validation-for="@Model.PropertyName" class="text-danger"></span>