Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Samples not working for Web API Help Page when using an Entity Framework Complex Type in the model

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?

like image 494
kkara Avatar asked Feb 22 '13 17:02

kkara


People also ask

How do you force a Web API to read a complex type from the URI?

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.

How do I add Entity Framework to Web API?

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.

How do I pass body parameters in Web API?

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.

What is FromBody and FromUri in Web API?

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.


1 Answers

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.

like image 92
Kiran Avatar answered Nov 11 '22 17:11

Kiran