I have an EF code first model that includes some Complex Types. Generating Web API controllers works without any problem, but when generating the Web API Help Page as described in http://blogs.msdn.com/b/yaohuang1/archive/2012/08/15/introducing-the-asp-net-web-api-help-page-preview.aspx then the samples don't get generated. The error message given is :
An exception has occurred while using the formatter 'JsonMediaTypeFormatter' to generate sample for media type 'application/json'. Exception message: One or more errors occurred.
The same thing happens for the rest of the media types. I know there was a problem some time ago with complex types and serialization but it was solved when the Json.NET formatter was included by default in Web API.
Could this be related? Anyone else having the same problem? Any ideas?
To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.
In the Solution Explorer, right-click on the Controllers folder and go to Add and click on Controller. In the next Add Scaffold wizard, select the Web API 2 Controller using Entity Framework and click on Add. Define the Model Class and for the Data Context class click on the Add button.
Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.
The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.
My guess is that this is most probably due to the referencing loops that your model has. For example, can you give a try in generating the help page by making the following change to the Json formatter. you should see the sample getting generated:
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
Also, you should see similar error even during runtime actually if you do not make the above settings.
For XmlFormatter and self referencing loops, you can look here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With