这里是我的测试类数据注释:StringLengthAttribute似乎并不奏效
class Test
{
[Required, StringLength(10)]
public string MyProperty { get; set; }
}
这里是我的控制台测试程序:
class Program
{
static void Main(string[] args)
{
var test = new Test {
MyProperty = "this is way more than 10 characters and should fail."
};
var context = new ValidationContext(test, null, null);
// No exception here! (why not?)
Validator.ValidateObject(test, context);
test.MyProperty = null;
// Exception here, as expected
Validator.ValidateObject(test, context);
}
}
出于某种原因,我没有得到一个当字符串长度过长时,验证异常。当我将该属性设置为null并重新验证时,确实收到了验证异常(如预期的那样)。任何想法为什么我的字符串长度注释没有被强制执行?