Samples not working for Web API Help Page when using an Entity Framework Complex Type in the model
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.
kkara
Updated on June 07, 2022Comments
-
kkara almost 2 years
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?
-
kkara about 11 yearsYou were absolutely right, it just happened that every model that had a referencing loop, also had a complex type. Thank you so much!
-
bbodenmiller over 10 yearsYou'll want to put this in WebApiConfig.cs.
-
Ebsan almost 10 yearsI was still getting weird $ref and $id tags when doing this. I found a better way: set the get on the child reference to it's parent as internal. Source: truncatedcodr.wordpress.com/2012/09/10/…
-
Psi-Ed over 7 yearsThe link for XMLFormatter and self-referencing loops is not working anymore
-
Akmal Salikhov over 7 years@Kiran Challa please update link about XmlFormatter and self referencing loops. Thanks!
-
Visual Micro almost 4 yearsFor XmlFormatter we need to set [DataContract(IsReference = true)] for each model and set all properties etc. in the model to [DataMember] or configure the xmlformatter per instance with preserveObjectReferences=true. see doc docs.microsoft.com/en-us/aspnet/web-api/overview/…