web-api POST body object always null
Solution 1:
FromBody is a strange attribute in that the input POST values need to be in a specific format for the parameter to be non-null, when it is not a primitive type. (student here)
- Try your request with
{"name":"John Doe", "age":18, "country":"United States of America"}
as the json. - Remove the
[FromBody]
attribute and try the solution. It should work for non-primitive types. (student) - With the
[FromBody]
attribute, the other option is to send the values in=Value
format, rather thankey=value
format. This would mean your key value ofstudent
should be an empty string...
There are also other options to write a custom model binder for the student class and attribute the parameter with your custom binder.
Solution 2:
I was looking for a solution to my problem for some minutes now, so I'll share my solution.
When you have a custom constructor within your model, your model also needs to have an empty/default constructor. Otherwise the model can't be created, obviously. Be careful while refactoring.
Solution 3:
I spend several hours with this issue... :( Getters and setters are REQUIRED in POST parameters object declaration. I do not recommend using simple data objects (string,int, ...) as they require special request format.
[HttpPost]
public HttpResponseMessage PostProcedure(EdiconLogFilter filter){
...
}
Does not work when:
public class EdiconLogFilter
{
public string fClientName;
public string fUserName;
public string fMinutes;
public string fLogDate;
}
Works fine when:
public class EdiconLogFilter
{
public string fClientName { get; set; }
public string fUserName { get; set; }
public string fMinutes { get; set; }
public string fLogDate { get; set; }
}
Solution 4:
If the any of values of the request's JSON object are not the same type as expected by the service then the [FromBody]
argument will be null
.
For example, if the age property in the json had a float
value:
"age":18.0
but the API service expects it to be an int
"age":18
then student
will be null
. (No error messages will be sent in the response unless no null reference check).
Solution 5:
This is a little old one and my answer will go down to the last place but even so I would like to share my experience.
Tried every suggestion but still having the same "null" value in a PUT [FromBody].
Finally found it was all about Date format while JSON serializing the EndDate property of my Angular Object.
No error was thrown, just received an empty FromBody object....