Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • ModelState.IsValid is true when model is null in Web API action method

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2
    • 0
    • 1.18k
    Comment on it

    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
     


    Web API call using any HTTP client tool (following screenshot uses Postman)


    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.

    ModelState.IsValid is true when model is null in Web API action method

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: