如何在 Web Api OData Web 服务中禁用格式化程序 [英] How to disable Formatters in Web Api OData web service

查看:18
本文介绍了如何在 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);

这篇关于如何在 Web Api OData Web 服务中禁用格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆