locked
Error in XML result when applying hateoas to my web api RRS feed

  • Question

  • So i created a new web api project using .net framework.

    first i created a class library project that has this link class below

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Access
    {
        public class Link
        {
            public string Href { get; set; }
            public string Rel { get; set; }
            public string Method { get; set; }
    
            public Link(string href, string rel, string method)
            {
                this.Href = href;
                this.Rel = rel;
                this.Method = method;
            }
        }
    }

    And this is my table class Test the got generated when i added a .net ADO to connect to my sql server. The table has 2 fields and i added the link field by code

    //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated from a template.
    //
    //     Manual changes to this file may cause unexpected behavior in your application.
    //     Manual changes to this file will be overwritten if the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------
    
    namespace Access
    {
        using System;
        using System.Collections.Generic;
    
        public partial class Test
        {
            public int Id { get; set; }
            public string Name { get; set; }
            
           //added by code
            public List<Link> Links { get; set; } = new 
            List<Link>();
        }
    }

    Now i created a new controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using Access;
    
    namespace Service.Controllers
    {
        public class Controller : ApiController
        {
    
           // GET api/Test
            [Route("api/Test", Name = "GetAll")]
            public IHttpActionResult GetAll()
            {
                using (TDBEntities entites = new 
                TDBEntities())
                {
                    return Ok(entites.Test.ToList());
                }
            }
    
            [Route("api")]
            public IHttpActionResult GetApi()
            {
                List<Link> links = new List<Link>
                {
                    new Link(Url.Link("GetAll",null), 
                    "All","GET"),
                };
                API aPI = new API
                {
                    Links = links
                };
                return Ok(aPI);
    
            }
    
     
        }
    
        public class API
        {
            public List<Link> Links { get; set; } = new 
            List<Link>();
        }
    }

    Now when i call the method GetApi from postman, i get a correct result from JSON

    {
        "Links": [
            {
                "Href": "https://localhost:1111/api/Test",
                "Rel": "All",
                "Method": "GET"
            }
        ]
    }

    but when i switch to XML i get this error: How to solve this??

    <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 'Access.Link' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for other supported types.</ExceptionMessage>
            <ExceptionType>System.Runtime.Serialization.InvalidDataContractException</ExceptionType>
            <StackTrace>   at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.ThrowInvalidDataContractException(String message, Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.CreateDataContract(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.DataContract.DataContractCriticalHelper.GetDataContractSkipValidation(Int32 id, RuntimeTypeHandle typeHandle, Type type)
       at System.Runtime.Serialization.XmlObjectSerializerContext.GetDataContract(Int32 id, RuntimeTypeHandle typeHandle)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
       at WriteArrayOfLinkToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )
       at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.InternalSerialize(XmlWriterDelegator xmlWriter, Object obj, Boolean isDeclaredType, Boolean writeXsiType, Int32 declaredTypeID, RuntimeTypeHandle declaredTypeHandle)
       at WriteAPIDiscoveryToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , ClassDataContract )
       at System.Runtime.Serialization.ClassDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
       at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)
       at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)
       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__22.MoveNext()</StackTrace>
        </InnerException>
    </Error>


    Wednesday, April 1, 2020 8:19 AM

All replies

  • This is related to how web API serializes data. Please post questions related to Web API in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, April 1, 2020 1:03 PM