0

In the hopes of supplying more metadata to my application, I wanted to wrap some extra information around my database queries (using plain on SQL data access, no Entity Framework or other ORMs).

I have an APIQueryResult object set up as:

string Status { get; set; }
string[] Errors { get; set; }
object[] Data { get; set;}

The Data is an array of my POCO object(s).

If I request JSON, then everything serializes just fine, including my metadata + object data. However, if I request XML, then I get the following error:

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

Note: This idea was inspired by Filip W (http://www.strathweb.com/2012/06/extending-your-asp-net-web-api-responses-with-useful-metadata/ ) but I didn't want to get as complicated as writing HttpHandlers, etc.

Is there a better way to provide at least error information back to the client if I can't return a normal class, or IEnumerable/List of class instances?

Thanks!

1 Answer 1

1

You could implement IXmlSerializable on your APIQueryResult object. With a bit of reflection it shouldn't be more than 20-30 lines with an XmlWriter to manually serialize that information. I guess it depends on how complex your DTOs are. The advantage of that is you have complete control over how what your XML looks like.

3
  • Thanks for this. I actually don't need XML; my application is expecting JSON. I was more concerned that the feature of the ASP.NET WebAPI that allows it to respond to different content types is breaking. It's something to do with Data Contracts, but the behind-the-scenes stuff here is way over my head. Commented May 12, 2013 at 5:45
  • 1
    @AR. If you only want JSON then remove all the other formatters from the config.Formatters collection and it won't try and serialize to XML. The problem is that the XmlSerializer and DataContractSerializer can't serialize an array of objects. They do certain performance optimizations that make serializing unknown types impossible. Commented May 12, 2013 at 12:27
  • Thanks Darrel - looks like that's the answer: "serializing unknown types is impossible" - at least for XML. Commented May 13, 2013 at 22:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.