Why .Net API controller parses string to int 0 for integer property instead of bad request

Viewed 62

I have a model class that has an integer property

public class Foo 
{
  public string Name {get; set;}
  public int Type {get; set;}
}

Type is an optional property, so when the value is not provided it will be 0, and based on that I can assign the default value.

But the issue is, when sending the string value to Type, it will parse that to int 0 instead of returning a bad request.

Ex:

{
  "Name": "my name",
  "Type: "This is invalid"
}

I tried adding validation, but the problem is when it reaches validation, the Type is equal to 0.

So I cannot differentiate the above request and the below request.

 {
     "Name": "my name"
 }

All I want is to return the bad request for the first request.

0 Answers
Related