XML formatting support in ASP.NET Web API OData

Topics: ASP.NET Web API
Jan 20, 2013 at 8:14 AM
Edited Jan 20, 2013 at 8:30 AM

Hi guys,

Is application/xml supported as content type for OData in latest nightly builds? I had problems getting it to work (json works fine).

EDIT: Seems like the issue was on my side. Switched to REST Console and now when I specify application/atom+xml as accepted content type, XML is being returned. $format does not seem to have any effect though.

Jan 20, 2013 at 4:34 PM

Yes, application/xml is a supported content type. We recently made the switch to application/json (minimal metadata variant) recently as the default format). $format is not supported out of the box. You have to do it through custom media mappings.

Jan 20, 2013 at 8:05 PM

Thanks for explanation, is there any easy way to change default format to xml?

Jan 24, 2013 at 6:54 PM

For the default format, it's a matter of how the OData media type formatters are ordered. The default order is JSON first and everything else after. To change it, you'll probably want to switch the order using per-controller configuration. Here's an example:

public class JsonLastAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        MediaTypeFormatterCollection formatters = controllerDescriptor.Configuration.Formatters;

        // Create a copy of the list of all JSON formatters.
        IEnumerable<MediaTypeFormatter> jsonFormatters = formatters.Where(f => f.SupportedMediaTypes.Any(
            m => m.MediaType == "application/json")).ToList();

        // Remove them from their current positions in the list.
        foreach (MediaTypeFormatter jsonFormatter in jsonFormatters)
        {
            formatters.Remove(jsonFormatter);
        }

        // Add them back to the end of the list.
        foreach (MediaTypeFormatter jsonFormatter in jsonFormatters)
        {
            formatters.Add(jsonFormatter);
        }
    }
}

Then, apply this attribute to your controller class(es). Or, if you have multiple controller classes and you want to share this behavior without having to specify the attribute each time, try creating a small base class:

[JsonLast]
public class JsonLastODataController : ODataController
{
}

David