Web API 2:[必填]值类型? [英] Web Api 2: [Required] for value types?
本文介绍了Web API 2:[必填]值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
仅在Web Api输入模型中使用[Required]
数据注释似乎会检查实例化为null的引用类型:
Using the [Required]
data annotation in Web Api input models only seems to check for reference types being instantiated to null:
public class MyInputModel
{
[Required] // This works! ModelState fails.
public CustomClass MyCustomProperty { get; set; }
}
在没有默认实例化的情况下,如何使它与值类型一起使用?
How can we get this to work with value types WITHOUT the default instantiation?
public class MyInputModel
{
[Required] // This is ignored because MyDouble is defaulted to 0
public double MyDouble { get; set; }
}
使用Nullable<Double>
是唯一的方法吗?我们不能创建一些自定义验证属性吗?
Is the only way through using Nullable<Double>
? Could we not create some custom validation attribute?
推荐答案
这是必需属性在内部工作的方式.
This is how the required attribute working internally.
override bool IsValid(object value) {
if (value == null) {
return false;
}
// only check string length if empty strings are not allowed
var stringValue = value as string;
if (stringValue != null && !AllowEmptyStrings) {
return stringValue.Trim().Length != 0;
}
return true;
}
所以与0值无关,因此必须使用Range属性进行检查
So nothing to do with the 0 value so you must check it with Range attribute
这篇关于Web API 2:[必填]值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文