I have an existing controller where [FromBody]
is working as expect in HttpPost
methods. When writing tests, I found it necessary to use a customer serializer in order to avoid a circular reference due to the parent object having a child that references the parent. The serializer uses these settings:
JsonSerializerSettings Settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto,
ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
ObjectCreationHandling = ObjectCreationHandling.Auto
};
The problem is that [FromBody]
is unable to parse the object produced by that serializer (it throws a Newtonsoft.Json.JsonSerializationException). However, if I change [FromBody]
to be dynamic, e.g.
public IActionResult Update([FromBody]dynamic json)
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<MyType>(json);
...
}
then I'm able to parse the object without a problem. This is confusing me, and I am wondering if I can override what WebApi does for [FromBody]
so that I can get the correct object without having to make every method accept a dynamic
parameter?