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

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

问题描述

我有一个必需的属性Model对象

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);
    }

如果我提交提交适当的请求(用模型)来操作方法我从ModeState.IsValid(真)的正确值。然而,当我提出无效请求(没有一个模型,因此模型为null)我得到一个错误的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).

我可以简单地检查是否该模型是在我的code空,但气味。这是一个预期的'功能'或的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:<一href=\"http://stackoverflow.com/questions/17923622/modelstate-isvalid-even-when-it-should-not-be\">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?

您还可以添加自定义过滤器来验证(无效)缺少字段和/或空值
<一href=\"http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api\">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

<一个href=\"http://www.strathweb.com/2012/10/clean-up-your-web-api-controllers-with-model-validation-and-null-check-filters/\">http://www.strathweb.com/2012/10/clean-up-your-web-api-controllers-with-model-validation-and-null-check-filters/

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

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