Search code examples
odatawebapi

How to disable Formatters in Web API OData web service


In my OData Web API web service I'm trying to disable all formatters except XML so that regardless of what the client sends in the Accept header, my web service will always return XML. My controller is derived from EntitySetController.

I think in a pure Web API web service you can just remove the unwanted formatters like in the code below, but it doesn't seem to work in my OData Web API web service. How can I get it to always return XML?

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // remove all formatters except XML
        MediaTypeFormatter xmlFormatter = config.Formatters.XmlFormatter;
        config.Formatters.Clear();
        config.Formatters.Add(xmlFormatter);

        ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
        modelBuilder.EntitySet<WorkItem>("WorkItems");
        IEdmModel model = modelBuilder.GetEdmModel();
        config.Routes.MapODataRoute(routeName: "OData", routePrefix: "odata", model: model);
...

Solution

  • I assume when you said OData and XML, you meant the OData XML and Atom formats specifically. If so, the following should work,

    var odataFormatters = ODataMediaTypeFormatters.Create();
    odataFormatters = odataFormatters.Where(
        f => f.SupportedMediaTypes.Any(
            m => m.MediaType == "application/xml" ||
                m.MediaType == "application/atom+xml" ||
                m.MediaType == "application/atomsvc+xml" ||
                m.MediaType == "text/xml")).ToList();
    
    config.Formatters.Clear();
    config.Formatters.AddRange(odataFormatters);