I\'m still learning web API, so pardon me if my question sounds stupid.
I have this in my StudentController
:
public HttpResponseMessage
In my case the problem was the DateTime
object I was sending. I created a DateTime
with "yyyy-MM-dd", and the DateTime
that was required by the object I was mapping to needed "HH-mm-ss" aswell. So appending "00-00" solved the problem (the full item was null because of this).
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).
Seems like there can be many different causes of this problem...
I found that adding an OnDeserialized
callback to the model class caused the parameter to always be null
. Exact reason unknown.
using System.Runtime.Serialization;
// Validate request
[OnDeserialized] // TODO: Causes parameter to be null
public void DoAdditionalValidatation() {...}
Just one more thing to look at... my model was marked as [Serializable] and that was causing the failure.
I was also trying to use the [FromBody], however, I was trying to populate a string variable because the input will be changing and I just need to pass it along to a backend service but this was always null
Post([FromBody]string Input])
So I changed the method signature to use a dynamic class and then convert that to string
Post(dynamic DynamicClass)
{
string Input = JsonConvert.SerializeObject(DynamicClass);
This works well.
Just to add my history to this thread. My model:
public class UserProfileResource
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public UserProfileResource()
{
}
}
The above object couldn't be serialized in my API Controller and would always return null. The issue was with Id of type Guid: everytime I passed empty string as an Id (being naive that it will automatically be converted to Guid.Empty
) from my frontend I received null object as [FromBody]
paramether.
Solution was either to
Guid
value Guid
to String