我有一个带Id属性的viewmodel
[Required]
public int Id { get; set; }
但我认为这个属性仅适用于字符串属性。
如果未设置Id,则Id的值为0且模型有效。
如果没有设置int属性的值,我该如何强制执行,模型将无效?
答案 0 :(得分:74)
使用Range
属性。
将最小值设置为1,将最大值设置为int.MaxValue
[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
答案 1 :(得分:43)
将类型更改为Nullable<int>
(快捷int?
)以允许null
值。
答案 2 :(得分:0)
对于.NET Core(可能还有更早的版本),您还可以创建一个自定义属性来执行范围验证,以便于重复使用:
public class Id : ValidationAttribute
{
protected override ValidationResult IsValid(
object value,
ValidationContext validationContext)
{
return Convert.ToInt32(value) > 0 ?
ValidationResult.Success :
new ValidationResult($"{validationContext.DisplayName} must be an integer greater than 0.");
}
}
在模型中像这样使用Id属性:
public class MessageForUpdate
{
[Required, Id]
public int UserId { get; set; }
[Required]
public string Text { get; set; }
[Required, Id]
public int ChannelId { get; set; }
}
当ID为<= 0
时,将返回以下错误消息:
UserId must be an integer greater than 0.
无需验证该值是否小于int.MaxValue(尽管很高兴在消息中显示该值),因为即使该值为int.MaxValue,API也会在此错误到达之前默认返回此错误。 +1:
The JSON value could not be converted to System.Int32
答案 3 :(得分:0)
如果您使用的是数据库,则应使用属性[Key]
和[DatabaseGenerated(DatabaseGenerated.Identity)]
,而Id
不应使用NULLABLE
。
答案 4 :(得分:0)
这与@Lee Smith的回答类似,但是使0为有效输入,这在某些情况下可能有用。
您可以做的是将int值初始化为另一个值,然后为0,如下所示:
[Range(0, int.MaxValue)]
public int value{ get; set; } = -1;
通过以下操作甚至可以支持除int.MinValue之外的所有值:
[Range(int.MinValue + 1, int.MaxValue)]
public int value{ get; set; } = int.MinValue;