While calling a Web API action method which receives parameter in model object, there are chances that client sending a request might not send any parameter at all. Well in such case you would be surprised to know that following check will return true though it is assumed to be returning false as the model itself is null.
if (ModelState.IsValid) // return true even when receiving model is null
{
}
Web API method
![](http://findnerd.s3.amazonaws.com/imagedata/6166/6166.png)
Web API call using any HTTP client tool (following screenshot uses Postman)
![](http://findnerd.s3.amazonaws.com/imagedata/6167/6167.png)
This weird behavior is due to the fact that ModelState.IsValid statement internally checks whether the count of errors associated with ModelState is either equals to zero or not, like in following statement.
Values.All(modelState => modelState.Errors.Count == 0)
In this case as there is not input so Values collection will be empty hence the statement ModelState.IsValid will evaluate to true.
One simple solution to handle this scenario will be to check the model parameter for null also.
if (product != null && ModelState.IsValid)
{
}
This kind of check could be done in a single place by defining and registering a custom attribute, but for the sake of simplicity this method of validation has been shown.
0 Comment(s)