我想确保我的模型的list属性不为空,因此我创建了 ValidationAttribute ,但值为List< long> 始终返回null,即使用 NoEmpty 修饰的属性的类型为List<长>。
为什么呢?以及如何正确地做到这一点?
public class NoEmptyAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var list = value as List<long>;
var msg = $"{validationContext.MemberName} can not bt empty";
if (list == null) return new ValidationResult(msg);
return list.Count == 0 ? new ValidationResult(msg) : ValidationResult.Success;
}
}
我更新了我的代码,现在工作正常:
public class NoEmptyAttribute: ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var list = value as IEnumerable;
var msg = $"{validationContext.MemberName} can not be null";
if (list == null) return new ValidationResult(msg);
return list.Cast<object>().Any() ? ValidationResult.Success : new ValidationResult(msg);
}
}
为什么值为List&lt; long&gt; 总是返回null,该值的类型为HashSet&lt;长&gt;。
答案 0 :(得分:1)
我写了一个单元测试(基于你的NoEmptyAttribute的代码),一切都按预期工作
[TestClass()]
public class NoEmptyAttributeTests
{
[TestMethod]
public void GetValidationResult_ListLongWithElements_ReturnsNull()
{
object obj = new object();
object value = new List<long> { 1, 2 };
ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
var noempty = new NoEmptyAttribute();
var result = noempty.GetValidationResult( value, ctx );
Assert.IsNull( result );
}
[TestMethod]
public void GetValidationResult_ListLongEmpty_ReturnsCannotBeEmpty()
{
object obj = new object();
object value = new List<long>();
ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
var noempty = new NoEmptyAttribute();
var result = noempty.GetValidationResult( value, ctx );
Assert.IsNotNull( result );
Assert.AreEqual( "Foo can not bt empty", result.ErrorMessage );
}
[TestMethod]
public void GetValidationResult_ListLongNull_ReturnsCannotBeEmpty()
{
object obj = new object();
object value = null;
ValidationContext ctx = new ValidationContext( obj ) { MemberName = "Foo" };
var noempty = new NoEmptyAttribute();
var result = noempty.GetValidationResult( value, ctx );
Assert.IsNotNull( result );
Assert.AreEqual( "Foo can not bt empty", result.ErrorMessage );
}
}