我有一个简单的问题(或没有)。

为什么当我验证对象时,下面的代码每次都验证一个零件。

如果DataAnnotations失败,则不会调用来自IValidatableObject的Validate。
如果DataAnnotations正常,则从IValidatableObject调用Validate。

我的问题是:为什么?我认为没有任何理由。我想念什么吗?

这是我的类(class)(例如):

class Foo : IValidatableObject
{
    [Required]
    public DateTime Date { get; set; }

    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var errors = new List<ValidationResult>();

        if (Date.Ticks > DateTime.Today.Ticks)
        {
            errors.Add(new ValidationResult("Some error.", new[] { "Date" }));
        }

        return errors;
    }
}

这是我的验证:
var dto = new Foo();

validationResults = new List<ValidationResult>();
var context = new ValidationContext(dto, null, null);

Validator.TryValidateObject(dto, context, validationResults, true);

// Force
//var model = dto as IValidatableObject;

//if (model != null)
//{
//    validationResults.AddRange(model.Validate(context));
//}

最佳答案

解决方案:

private void ValidateIValidatableObject(IValidatableObject validatableObject, IList<ValidationResult> errors)
{
    var validations = validatableObject.Validate(null).ToList();

    validations.Where(vr => vr.MemberNames == null)
        .ToList()
        .ForEach(vr => errors.Add(new ValidationResult(vr.ErrorMessage)));

    validations.Where(vr => vr.MemberNames != null)
        .SelectMany(vr => vr.MemberNames.Select(mn => new { MemeberName = mn, vr.ErrorMessage }))
        .ToList()
        .ForEach(vr => errors.Add(new ValidationResult(vr.ErrorMessage, new string[] { vr.MemeberName })));
}

用法:
IList<ValidationResult> errors = new List<ValidationResult>();

ValidationContext context = new ValidationContext(model, null, null);
Validator.TryValidateObject(model, context, errors, true);

if (model is IValidatableObject validatableObject)
{
    ValidateIValidatableObject(validatableObject, errors);
}

积分:https://github.com/aspnet/Mvc/issues/5366

09-25 18:30