How to disable Formatters in Web Api OData web ser

2019-07-23 10:57发布

问题:

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);
...

回答1:

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);


标签: api web odata