ModelSate.IsValid returns 发布到 Web Api 操作时为真,结果模型为空

ModelSate.IsValid returns true when posting to Web Api action and resulting Model is null

使用 Chrome PostMan,我注意到如果我 post 一个动作方法而不传递任何表单参数 ModelState.IsValid returns true 即使我有 [Required] 在模型属性上设置验证属性。

奇怪的是,作为参数传递的 Model 的值是 null,即使 IsValidtrue

有没有办法从OnActionExecuting拦截Model来检查模型是否为空并适当处理这种情况,或者有更好的方法来确保IsValidreturns false 在这种情况下?

编辑:我能找到的最接近 "official" 洞察力的是 ASP.NET 上的 post。他们示例中显示的代码首先测试模型是否为空,然后在单独的步骤中检查模型是否有效。

ASP.NET Model Binding

这在下面的 link 中得到了回答。这是 post 中的一些内容:

ModelState.IsValid 内部检查 Values.All(modelState => modelState.Errors.Count == 0) 表达式。

因为没有输入值集合将为空所以 ModelState.IsValid 将为真。

因此您需要明确处理这种情况:

if (user != null && ModelState.IsValid)
{

}

Source Post

没有您的模型数据,就不可能真正为您提供帮助。

但是,您的问题源于以下原因:

  • ModelState.IsValid :调用时,本质上会执行以下操作:Values.All(m => m.Errors.Count == 0)。由于集合为空,它仍将验证为 true。由于集合没有错误。

要正确说明信息,您需要执行以下操作:

// If Invalid
if(model == null && !ModelState.IsValid)
     return View("Error");

// If Vaild
if(model != null && ModelState.IsValid)
     return View("Valid");

The ModelState.IsValid represents the state of an attempt to bind a posted form to an action method, which includes the validation information. Another potential approach would be to do a Count on the KeyValuePair within the Dictionary.

if(ModelState.Count != 0)
     return View("Valid");

另一个建议,希望这能澄清。 IsValid 将根据潜在错误触发其计数。如果 Collection 中不存在,它将始终 return true.

文档: