title: How to avoid invalid error in ModelState when deserializing a json
body: <p>I'm writing an API controller with C#. I'm leveraging the ModelState to do the model validation. E.g. checking the length of a string field, or checking if an int field exceed the maximum.</p>
  
  <p>But I found an issue, sometimes it does not work as expected. For example, here I have a model with two fields:</p>
  
  <pre><code>public int A { get; set; }
  public bool B { get; set; }
  </code></pre>
  
  <p>Then my request payload looks like following:</p>
  
  <pre><code>{
     "A": 123.4,
     "B": true
  }
  </code></pre>
  
  <p>Obviously the A is in a invalid format, it should be int but I gave it a float. So I got an error in ModelState: <code>Input string '123.4' is not a valid integer. Path 'A', line x, position x.</code>. This totally make sense.</p>
  
  <p>But another error occurs in the ModelState at the same time: <code>Unexpected token when deserializing object: Boolean. Path 'B', line x, position x.</code>.</p>
  
  <p>It seems that when A is not an int, C# will have errors in deserializing the rest part of the json. How could I avoid this? I hope there's only the first error in the ModelState.</p>
  
  <p>Thank you all!</p>
  
  <p>------------------------------EDIT--------------------------------</p>
  
  <p>Many thanks for the help. I'd like to add some comments here. For sure I used <code>ModelState.IsValid</code> to check if the payload is valid. And the result is false. Which is correct. But the mistake here is, only the first field A is invalid, but B is valid. So I wish to have only A's error in the ModelState.</p>