ModelState 对空模型有效 [英] ModelState is valid with null model

查看:22
本文介绍了ModelState 对空模型有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有必需属性的模型对象

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 values http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

http://www.strathweb.com/2012/10/clean-up-your-web-api-controllers-with-model-validation-and-null-check-filters/

这篇关于ModelState 对空模型有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆