locked
The 'ObjectContent`1' type failed to serialize the response body for content type 'text/xml; charset=utf-8' RRS feed

  • Question

  • User-585883700 posted

    I get normal response from API when I request content type 'text/json and the problem when I request content type 'text/xml; I get this message An error has occurred.The 'ObjectContent1' type failed to serialize the response body for content type 'text/xml; charset=utf-8'.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace /><InnerException><Message>An error has occurred.</Message><ExceptionMessage>There was an error generating the XML document.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace> at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.&lt;WriteBufferedResponseContentAsync&gt;d__1b.MoveNext()</StackTrace><InnerException><Message>An error has occurred.</Message><ExceptionMessage>The type System.Collections.Generic.List1[[testtransotels.data.cities, testtransotels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context.System.InvalidOperationException at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write2_anyType(Object o)

    my code as you see

       private datacontext db = new datacontext();
     public object Post([FromBody]Request Request)
        {
            return db.Student;
    
        }
     public class Student
    {
        [DataMember]
    
        public string StudentID { get; set; }
    
        [DataMember]
    
        public string StudentName { get; set; }
        [DataMember]
    
        public string StudentCode { get; set; }
    }
    Wednesday, August 24, 2016 6:31 PM

Answers

  • User36583972 posted

    Hi yhyasoft,

    When you request the Web API with content type 'text/xml' and serialize the Object type. You will fail.

    You can try the following solution.

    1: Change your Web API method return type as  List<Student>

    Web API:

         [AllowAnonymous]
            public List<Student> Post()
            {
                List<Student> lists = new List<Student>() {
                    new Student() { StudentCode="1", StudentID="2", StudentName="tsts" },
                      new Student() { StudentCode="2", StudentID="332", StudentName="tsts22" },
                };
                return lists;
               // string httpContent = Request.Content.ReadAsStringAsync().Result;
            }
    

    Client:

             HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url");//
                request.Method = "Post";
                request.KeepAlive = true;
                request.ContentLength = 0;
                request.ContentType = "text/xml";//text/json   , appication/json
                request.Accept = "application/xml";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                string myResponse = "";
                using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
                {
                    myResponse = sr.ReadToEnd().ToString();
                }
                Response.Write(myResponse);

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 25, 2016 4:22 AM