1

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 derrived 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);
...
Iman Mahmoudinasab
  • 6,861
  • 4
  • 44
  • 68
Rn222
  • 2,167
  • 2
  • 20
  • 36

1 Answers1

2

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);
Iman Mahmoudinasab
  • 6,861
  • 4
  • 44
  • 68
RaghuRam Nadiminti
  • 6,718
  • 1
  • 33
  • 30