How to disable Formatters in Web Api OData web service

浪尽此生 提交于 2020-01-05 05:39:08

问题


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


来源:https://stackoverflow.com/questions/18213737/how-to-disable-formatters-in-web-api-odata-web-service

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!