I am creating POST API in .NET. I have following class.
public class Item
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
Following is the controller method.
1st approach:-
public IHttpActionResult Post([FromBody]Item item)
{
// some code
return Ok();
}
2nd approach:-
public IHttpActionResult Post()
{
Item item = null;
var reqContent = Request.Content.ReadAsStringAsync().Result;
if (reqContent != null)
{
item = JsonConvert.DeserializeObject<Item>(reqContent);
}
// some code
return Ok();
}
The problem is when I send age=''
or age=null
in a request, In the first approach, it takes item.Age=0
but in the second approach, it throw an exception Error converting value {null} to type 'System.Int32'.
Why this is happening that I am not able to understand.
My guess is that in FromBody
null value handling for such type of conversation is handle, but in JsonConvert.DeserializeObject
it is not handled.
Is it right? Or there is some other reason for the upper behavior.