The Challenge
I was building a standard ASP.NET EntityFramework / WebApi / Swagger project. Attempting something a bit new, I decided my controller would return a CreatedAtRoute HttpActionResult. The code goes something a little like this:
[HttpPut]
public IHttpActionResult AddMyObject([FromBody] MyObject newObject)
{
// validation stuff
// context writing stuff which creates the resulting 'myObject' object in the database
return CreatedAtRoute("FindMyObject", new {id = myObject.MyObjectId}, myObject);
}
The issue I had was the following error:
"ExceptionMessage": The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'."
"InnerException":{
"ExceptionMessage": "Self referencing loop detected for property 'MyObject' with type 'SomePath.MyObject'. Path 'MyObjectProperty[0]'",
"ExceptionType": Newtonsoft.Json.JsonSerializationException"
}
Solution
A quick google search led me to Stack Overflow where I learned how to turn on loop handling. I also saw a previous Stack Overflow answer in which I learned to change the default (and ordering) of response formatters.
I decided to force my API to only emit JSON. I've been using AutoRest to generate WebClient classes in our projects' service layers, and JSON is arguably easier to use on the front end than XML. Restricting the output was easily accomplished by adjusting my App_Start.WebApiConfig.Register() method to this:
public static void Register(HttpConfiguration config)
{
// Set default order of formatters
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
// Ignore JSON reference loops
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
// Web API routes
...
}
Software Development Nerd