I am building an API in ASP.NET MVC4 Web API, and one of my actions returns XML (currently in the form of an XElement). I have no control of the data, I am just passing it on. There is no standard object that I can de-serialize it to.
public Task<XElement> Get( string queryName, string query )...
What I want to do is use a MediaTypeFormatter to convert that to JSON if it is requested as such. I have started writing the MediaTypeFormatter and hooked it up, but when I call the “Get” on the controller, it calls
protected override bool CanWriteType( Type type )
{
return true;
}
in the MediaTypeFormatter, but never gets as far as the OnWriteToStreamAsync method. The result is just the XML as a string, e.g.
"<testXmlHere\/>"
Does anyone have any idea how to fix this up?
Thanks
Your custom formatter is probably inserted in the formatters list after the
JsonMediaTypeFormatterin the formatters collection. That formatter can writeXElement, and it does so by writing the XML representation as a JSON string (whether this is a good or bad idea is another discussion). When adding your formatter to the collection, use theInsertinstead of theAddmethod: