locked
Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type..... RRS feed

  • Question

  • Hi I am new to web Api, and  I am getting this error:

    <Error>

    <Message>An error has occurred.</Message>

    <ExceptionMessage>The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.</ExceptionMessage>

    <ExceptionType>System.InvalidOperationException</ExceptionType>

    <StackTrace/>

    <InnerException>

    <Message>An error has occurred.</Message>

    <ExceptionMessage>Type 'System.Data.Entity.DynamicProxies.Employee_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338' with data contract name

    'Employee_0D7A537351492F8D419F58EA70B1240500CF0FFF354951D83FA225EA973C5338:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not

    expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute

    attribute or by adding them to the list of known types passed to DataContractSerializer.</ExceptionMessage>

    <ExceptionType>System.Runtime.Serialization.SerializationException</ExceptionType>


    And  My LINQ query in action method is:

    public Employee GetEmployees()

            {

                Employee employees =(from e in db.Employees

                                select e).First();

                return employees;

    }


    NOTE: when I debugged this LINQ its working fine.i.e. its returning proper values from DataBase.

    Please Help. Thnx in advance. 

    • Changed type Tamal K Dey Tuesday, October 9, 2012 5:51 AM
    Monday, October 1, 2012 6:48 AM

Answers

  • Hi Sameer and Kap.dave,

    After long struggle I got the solution of my problem....
    just added this two lines in my WebApiConfig.cs file...

    var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling =                Newtonsoft.Json.PreserveReferencesHandling.Objects;
     config.Formatters.Remove(config.Formatters.XmlFormatter);


    Tamal Kanti Dey (Software Developer) Mindfire Solutions,Bangalore India

    • Marked as answer by Tamal K Dey Tuesday, October 9, 2012 5:52 AM
    Monday, October 8, 2012 10:32 AM
  • Hi my friend, I gave the same error, and a fixed it with a line in the application_start on the global.asax:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

    I hope that help you!

    Julio Avellaneda
    Core Group Comunidad BDotNet
    MVP | MCTS | MCC | MCS
    Blog !!

    • Marked as answer by Tamal K Dey Tuesday, October 9, 2012 5:52 AM
    Tuesday, October 9, 2012 5:41 AM

All replies

  • Why the thread type is set to "Discussion"? Shouldn't it be "Question"?

    If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.

    Monday, October 1, 2012 9:00 AM
  • oops...my bad.

    its my first time.....

    by any chance do u have any idea....plz help me with this...


    Tamal Kanti Dey (Software Developer) Mindfire Solutions,Bangalore India

    Monday, October 1, 2012 9:19 AM
  • See if you have any non-'native' types (anything that isnt int, string, DateTime, etc) in your Employee class definition. For all such types
    you will need to add a [KnownType] attribute that might be passed back, like this:

    [KnownType(typeof(yourtype))]

    If not of a concern, you may want to post your Employee object definition here so I can help exactly. Thanks.

    HTH

    Sameer


    If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.

    Monday, October 1, 2012 9:31 AM
  •  

    Hi Sameer,
    this is my Employee class..

    public partial class Employee
        {       
            public int Id { get; set; }
            public string EmpName { get; set; }
            public string EmpCity { get; set; }
            public int EmpSalary { get; set; }
            public int EmpDept { get; set; }
               
     public virtual Department Department { get; set; }
        }

    still I m having this problem...

    thnx in advance,

    Tamal


    Tamal Kanti Dey (Software Developer) Mindfire Solutions,Bangalore India

    Wednesday, October 3, 2012 8:07 AM
  • I can see that you have a property of type Department, for all such properties you got to add

    [KnownType(typeof(yourtype))]

    attribute as followed:

    [KnownType(typeof(Department))]

    public partial class Employee
    {
    ...
    }

    Note you will have to do the same for all nested custom types as well, e.g. if Department contains another property with custom type then add KnownType attribute for that type as well on top of Employee class definition.


    If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.


    Wednesday, October 3, 2012 8:56 AM
  • same problem,

    <Error>
    <Message>An error has occurred.</Message><ExceptionMessage>
    The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
    </ExceptionMessage>
    <ExceptionType>
    System.InvalidOperationException
    </ExceptionType>
    
    <StackTrace/>
    <InnerException>
    <Message>An error has occurred.</Message><ExceptionMessage>
    Type 'System.Data.Entity.DynamicProxies.Employee_2A11188F0CDFBF33C95FAFE62B81DD98E98D69C23C92A9E81C208CBC51EB5B80' with data contract name 'Employee_2A11188F0CDFBF33C95FAFE62B81DD98E98D69C23C92A9E81C208CBC51EB5B80:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer
    .</ExceptionMessage><ExceptionType>
    System.Runtime.Serialization.SerializationException
    </ExceptionType>


    Tamal Kanti Dey (Software Developer) Mindfire Solutions,Bangalore India

    Wednesday, October 3, 2012 9:43 AM
  • Okay, my final try...

    Please keep the knowtype attr. as it is and remove the virtual keyword in the department property from following line and then give it a try. If this works, we know we have to concentrate on getting the serialization to work with virtual keyword in place which I believe is added for lazy loading and change tracking to work as per entity f/w.

    public virtual Department Department { get; set; }


    If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.

    Wednesday, October 3, 2012 10:00 AM
  • If the issue is due to virtual keyword (added for lazy loading), then you can keep it whilst getting the serialization work by marking

    ProxyCreationEnabled = false;

    on either dbcontext (EF 4.1) or objectcontext (EF 4.0) as suggested in following links:

    http://stackoverflow.com/questions/7276507/serializable-classes-and-dynamic-proxies-in-ef-how

    http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/1c37447a-e303-4947-a3ee-d2e6592aac0a

    Thanks

    Sameer


    If this answers your question, please Mark it as Answer. If this post is helpful, please vote as helpful.

    Wednesday, October 3, 2012 10:10 AM
  • I am having this same problem.  I am returning an array of objects containing non-virtual primitives.
    Friday, October 5, 2012 3:45 PM
  • Hi Sameer and Kap.dave,

    After long struggle I got the solution of my problem....
    just added this two lines in my WebApiConfig.cs file...

    var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling =                Newtonsoft.Json.PreserveReferencesHandling.Objects;
     config.Formatters.Remove(config.Formatters.XmlFormatter);


    Tamal Kanti Dey (Software Developer) Mindfire Solutions,Bangalore India

    • Marked as answer by Tamal K Dey Tuesday, October 9, 2012 5:52 AM
    Monday, October 8, 2012 10:32 AM
  • Hi my friend, I gave the same error, and a fixed it with a line in the application_start on the global.asax:

    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

    I hope that help you!

    Julio Avellaneda
    Core Group Comunidad BDotNet
    MVP | MCTS | MCC | MCS
    Blog !!

    • Marked as answer by Tamal K Dey Tuesday, October 9, 2012 5:52 AM
    Tuesday, October 9, 2012 5:41 AM
  • Hi ! I ran into the exact same problem. It happens in Visual Studio 2012 with the MVC 4 WebApi using  Entity Framework. In the samples I saw with MVC 3, it returned xml when called from a browser request. But I was never able to get the XML reponse as I kept getting this error.

    The fix proposed here (reference handling by Json formatters) works, but I really don't like not knowing what I do and just cut / paste stuff. Can anyone explain us why is that happening from the VS template and is that fix good or just an ugly patch ? What if someone does want XML ? He'll have to trick an XmlFormatter I guess ?

    Wednesday, January 16, 2013 1:17 PM
  • FYI, I also found that disabling the proxy creation by the dbcontext works and gives me the XML response on a browser call. I'm sure it has some drawbacks too, and there is still not a lot of documentation about it. You can do it on controller level or in the DBContext constructor.

    This post explains it a little bit :

    http://stackoverflow.com/questions/8173524/webapi-with-ef-code-first-generates-error-when-having-parent-child-relation

    Wednesday, January 16, 2013 3:19 PM
  • Thank you! This helps me a lot.

    It seems that the xml serializer has some limit against the inherited properties. So this code is actually removing the xml formatter and use only the json formatter only.

    Friday, May 24, 2013 5:32 AM
  • This works for Json requests, but i still get the error on xml responses. Any suggestions?
    Tuesday, June 4, 2013 6:14 PM
  • Posting from my personal account:

    Depending on what exactly is failing to serialize, it might help you to do one of the following:

    (1) Mark as [XmlIgnore] any members on your class that you don't want to be serialized as XML.

    (2) If the serialization is happening as part of an OData method (ie, you have a controller inheriting from EntitySetController<yourType> or any derived type), than in your WebApiConfig class (or wherever you set up your model builder and WebApi route config), you can tell the OData formatter that does the serialization to ignore any properties that cause problems.  For example:
       
       var modelBuilder = new ODataConventionModelBuilder();
       modelBuilder.Entity<MyClassName>().Ignore(item => item.UnserializableProperty);


    SoftSource Consulting

    Tuesday, October 8, 2013 9:06 PM
  • Got exactly the same problem with primitive objects containing only of two strings without any EF.

    The trick with adding the json formatter and removing the xml formatter did it, but I'm still curious why that happens.

    I'm purely returning a "list.AsQueryable()" containing those objects:

        [Serializable]
        public class Product : IProduct {
            string _name;
            string _photo;
    
            public Product( string name) {
                Name = name;
                Photo = "No Photo";
            }
    
            public string Name {
                get {
                    return _name;
                }
                set {
                    V.NotEmpty(value, "name");
                    _name = value;
                }
            }
    
            public string Photo {
                get {
                    return _photo;
                }
                set {
                    V.NotEmpty(value, "name");
                    _photo = value;
                }
            }
        

    Any help is appreciated!

    Thx

    Sheer

    Sunday, October 27, 2013 9:25 PM
  • This eliminates the ability to output in xml. If this works for you, that's great, but this is not the "solution" to the problem for those who actually want to output in xml.
    Thursday, December 12, 2013 8:08 PM
  • again, this "fixes" the issue only for those who only want json output.
    Thursday, December 12, 2013 8:10 PM
  • This is the best answer as it fixes the problem without disabling xml output.
    Thursday, December 12, 2013 8:11 PM
  • Cheers for that.

    It solved my issue :)
    Thursday, July 3, 2014 3:21 PM
  • Just add a DataMemeber attribute to each property you want serialized in json. It's that simple. And...no need to get rid of virtual.

    You can EF 4T templates to generate that for you!

    Friday, September 12, 2014 5:03 PM
  • I created an account just to thank you for this answer!
    Tuesday, February 23, 2016 2:32 PM
  • I created an account just to thank you for this answer!

    In the future,  ASP.NET Web API issues can be discussed at the below forum.

    http://forums.asp.net/1246.aspx/1?Web+API

    Tuesday, February 23, 2016 4:29 PM
  • Thank U mr Tamal Kanti Dey 

    Tuesday, September 27, 2016 11:54 AM