如何在 Web Api OData Web 服务中禁用格式化程序

如何在 Web Api OData Web 服务中禁用格式化程序

问题描述:

在我的 OData Web API Web 服务中,我试图禁用除 XML 之外的所有格式化程序,以便无论客户端在 Accept 标头中发送什么,我的 Web 服务都将始终返回 XML.我的控制器是从 EntitySetController 派生的.

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.

我认为在纯 Web API Web 服务中,您可以像下面的代码一样删除不需要的格式化程序,但它在我的 OData Web Api Web 服务中似乎不起作用.我怎样才能让它总是返回 XML?

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

我假设当您说 OData 和 XML 时,您特指 OData XML 和 Atom 格式.如果是这样,以下应该有效,

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