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

11,808

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.

Share:
11,808
kkara
Author by

kkara

Updated on June 07, 2022

Comments

  • kkara
    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
    kkara about 11 years
    You were absolutely right, it just happened that every model that had a referencing loop, also had a complex type. Thank you so much!
  • bbodenmiller
    bbodenmiller over 10 years
    You'll want to put this in WebApiConfig.cs.
  • Ebsan
    Ebsan almost 10 years
    I 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
    Psi-Ed over 7 years
    The link for XMLFormatter and self-referencing loops is not working anymore
  • Akmal Salikhov
    Akmal Salikhov over 7 years
    @Kiran Challa please update link about XmlFormatter and self referencing loops. Thanks!
  • Visual Micro
    Visual Micro almost 4 years
    For 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/…