Я использую 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);
}
Что здесь не так?