我在这里讨论了同样的问题:How to do Integer model validation in asp.net mvc 2但[Range]解决方案不适用于asp.net核心。
有没有办法在模型验证期间执行数据类型检查?
我有这个型号:
public class Example
{
[Required]
[Range(1, int.MaxValue, ErrorMessage = "Should be int!")]
public int? SystemID { get; set; }
...
}
通过此验证:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
context.Result = new BadRequestObjectResult(context.ModelState);
}
}
}
如果我将一个字符串放入SystemId,我会得到:
{
"SystemID": [
"The input was not valid."
]
}