问题描述
我有一个具有必需属性的模型对象
I have a Model object with a required attribute
public class ApiPing
{
[Required]
public DateTime ClientTime { get; set; }
public DateTime ServerTime { get; set; }
}
我有一个检查模型状态的控制器方法.
I have a Controller method that checks model state.
public IHttpActionResult Ping(ApiPing model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
model.ServerTime = DateTime.UtcNow;
return Ok(model);
}
如果我向 action 方法提交一个正确的请求(带有模型),我会从 ModeState.IsValid (true) 获得正确的值.但是,当我提交一个无效请求(没有模型,所以模型为空)时,我得到一个错误的 ModelState.IsValid(也是如此).
If I submit a submit a proper request (with a model) to the action method I get an correct value from ModeState.IsValid (true). However, when I submit an invalid request (without a model, so the model is null) I get an erroneous ModelState.IsValid (also true).
我可以简单地检查我的代码中的模型是否为空,但这很糟糕.这是 ModelState 验证中的预期功能"还是错误?难道我做错了什么 ?是我期待太多了吗?
I could simply check if the model is null in my code, but that smells. Is this an intended 'feature' or a bug in ModelState validation? Am I doing something wrong ? Am I expecting too much ?
推荐答案
我以前也遇到过同样的问题,答案已经在一些论坛中找到了,甚至在 SO:ModelState.IsValid 即使不应该?
I had the same problem before and the answer is already available in a few forums and even here at SO: ModelState.IsValid even when it should not be?
您还可以添加自定义过滤器来验证(使)缺失的字段和/或空值http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
You can also add a custom filter to validate (invalidate) missing fields and/or null valueshttp://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
这篇关于ModelState 对空模型有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!