【问题标题】:Validator.TryValidateProperty throws ArgumentExceptionValidator.TryValidateProperty 抛出 ArgumentException
【发布时间】:2018-11-11 17:05:02
【问题描述】:

我使用 ListValidation

public class Test
    {

        [ListValidation(ErrorMessage ="wrong")]
        public List<string> Listt { get; set; }
    }

ListValidation 实现

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class ListValidationAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var list = value as IList;
            if (list != null)
            {
                return list.Count > 0;
            }
            return false;
        }
    }

当我测试它时

Test t = new Test();
            List<string> str = new List<string>();
            str.Add("haha");
            str.Add("hoho");

            t.Listt = str;

            JsonResult json = ModelValidation.ValidateProperty(t, nameof(t.Listt));

它抛出ArgumentException

{System.ArgumentException: The value for property 'Listt' must be of type 'System.Collections.Generic.List`1[System.String]'.
Parameter name: value
   at System.ComponentModel.DataAnnotations.Validator.EnsureValidPropertyType(String propertyName, Type propertyType, Object value)
   at System.ComponentModel.DataAnnotations.Validator.TryValidateProperty(Object value, ValidationContext validationContext, ICollection`1 validationResults)
   at EArchive.Infrastructure.ModelValidation.ValidateProperty(Object obj, String property) in C:\Users\haha\ModelValidation.cs:line 54}

ValidateProperty 实现

public static JsonResult ValidateProperty(object obj, string property)
        {
            ValidationContext context = new ValidationContext(obj)
            {
                MemberName = property
            };

            List<ValidationResult> results = new List<ValidationResult>();



            bool valid = Validator.TryValidateProperty(property, context, results);

            if (!valid) // there is no error and everything is good
            {
                return null;
            }

            string errors = "";

            // fetch all errors happened in the property.
            foreach (ValidationResult result in results)
            {
                errors += result.ErrorMessage + "\n <br>";
            }


            Dictionary<string, string> err = new Dictionary<string, string>()
                {
                    { "status", "fail" },
                    { "message", errors }
                };

            return new JsonResult(err);

        }

这里有什么问题?

【问题讨论】:

    标签: c# validation model-view-controller asp.net-core attributes


    【解决方案1】:

    Validator.TryValidateProperty 期望第一个参数 (object value) 是要测试属性的值,而不是属性的名称。在您的示例中,您传递的是字符串 Listt 而不是值 of t.Listt。为了使它适用于您的目的,您需要更改您的 ValidateProperty 函数,如下所示:

    public static JsonResult ValidateProperty(object propertyValue, string propertyName, object sourceObject)
    {
        ValidationContext context = new ValidationContext(sourceObject)
        {
                MemberName = propertyName
        };
    
        List<ValidationResult> results = new List<ValidationResult>();
    
        bool valid = Validator.TryValidateProperty(propertyValue, context, results);
    
        // ...
    

    然后,只需相应地更新您的呼叫站点:

    JsonResult json = ModelValidation.ValidateProperty(t.Listt, nameof(t.Listt), t);
    

    这是我用作此答案的灵感的博客文章:https://gigi.nullneuron.net/gigilabs/simple-validation-with-data-annotations/

    【讨论】:

      猜你喜欢
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2021-12-01
      • 2010-10-17
      • 2020-10-26
      • 1970-01-01
      相关资源
      最近更新 更多