I had a similar experience with a WebAPI application recently. The application had been working correctly in my test environment, but when we ran a build off the build server the application failed to deserialize the object and always set the parameter following [FromBody] to null.
The root cause was the web.config and packages.config specifying Json.NET 6.0.4 and the NuGet package that was in the bin was 10.0.3.
The model binding kind of looks like a black box from the outside at first. Especially since it can quietly return a null with no indication as to what is wrong. On this Microsoft page under the heading Testing Object Serialization there is an example of how to test serialization and deserialization:
string Serialize<T>(MediaTypeFormatter formatter, T value)
{
// Create a dummy HTTP Content.
Stream stream = new MemoryStream();
var content = new StreamContent(stream);
/// Serialize the object.
formatter.WriteToStreamAsync(typeof(T), value, stream, content, null).Wait();
// Read the serialized string.
stream.Position = 0;
return content.ReadAsStringAsync().Result;
}
T Deserialize<T>(MediaTypeFormatter formatter, string str) where T : class
{
// Write the serialized string to a memory stream.
Stream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(str);
writer.Flush();
stream.Position = 0;
// Deserialize to an object of type T
return formatter.ReadFromStreamAsync(typeof(T), stream, null, null).Result as T;
}
// Example of use
void TestSerialization()
{
var value = new Person() { Name = "Alice", Age = 23 };
var xml = new XmlMediaTypeFormatter();
string str = Serialize(xml, value);
var json = new JsonMediaTypeFormatter();
str = Serialize(json, value);
// Round trip
Person person2 = Deserialize<Person>(json, str);
}
When I put the above code in my application and ran it Visual Studio threw an exception in both the serialize and deserialize functions. The exception clearly stated that loading of Json.net version 6.0.4 had failed. Which led me to discover that version 10.0.3 was in the bin instead of 6.0.4. I right clicked on the project clicked manage NuGet Packages... in the context menu. Then removed and re-added the Json.net NuGet package. Doing that set the Json.net NuGet package in the bin and updated the packages.config and web.config with matching version numbers.