Web Api 2: [Required] for value types?

别等时光非礼了梦想. 提交于 2019-12-10 19:31:04

问题


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; }
}

Is the only way through using Nullable<Double>? Could we not create some custom validation attribute?


回答1:


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;
    }

So nothing to do with the 0 value so you must check it with Range attribute




回答2:


you can use the range attribute.

[Range(0, 99)]
public double MyDouble { get; set; }



回答3:


try making value type Nullable e.g. public double? MyDouble { get; set; }



来源:https://stackoverflow.com/questions/31947065/web-api-2-required-for-value-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!