Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState is valid with null 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); } 

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).

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 ?

like image 711
nVentimiglia Avatar asked Nov 08 '13 03:11

nVentimiglia


People also ask

Can ModelState be null?

This indicates that the model is required and can not be null . You can also use with a custom message: [ValidateModelState] public IHttpActionResult Create([Required(ErrorMessage = "Custom message")] UserModel data) {...

Does ModelState IsValid check for NULL?

The ModelState. IsValid property (ApiController) merely checks for a zero validation error count for a passed model while ignoring the nullability of the object instance itself.

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.


1 Answers

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?

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/

like image 103
julianox Avatar answered Oct 11 '22 08:10

julianox