设置默认的WebAPI格式化 [英] Set the default WebAPI formatter

查看:95
本文介绍了设置默认的WebAPI格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用的WebAPI以模仿传统系统的处理,作为结果,我们想默认响应格式化器以下,XMLFormatter而不是JsonFormatter。其原因是,一些给该服务的现有呼叫的不提供接受:HTTP头字段

We are using WebAPI to mimic the handling of a legacy system, as a result we would like the default response formatter to the XmlFormatter and not the JsonFormatter. The reason is that some of the existing calls to the service do not supply the Accept: HTTP header field.

我可以通过从格式化程序集合除去JsonFormatter实现这一点,然后重新添加它,迫使它是在链的末端

I can achieve this by removing the JsonFormatter from the Formatters collection and then re-adding it, forcing it to be at the end of the chain.

这个然后导致使用下,XMLFormatter默认格式的响应。虽然它的工作原理,它只是不觉得正确的,虽然我动JSON来收集的背后,有没有保证下,XMLFormatter是在收集的前面。

This then result in the default format response using the XmlFormatter. Although it works, it just doesn't feel correct and although I am moving Json to the back of the collection, there is no guarantee that the XmlFormatter is at the front of the collection.

创意/想法?

感谢

推荐答案

只需按正确的顺序添加格式化。如果的ASP.NET Web API查找两个格式化为相同的内容类型,它会选择第一个,因此是非常重要的在右的顺序添加格式化

Just add formatters in the right order. If ASP.NET Web API finds two formatters for the same content type, it will pick the first one so it is very important to add formatters in the right order.

//somewhere in Web Api config
config.Formatters.Clear();
config.Formatters.Add(new XmlMediaTypeFormatter());
config.Formatters.Add(new JsonMediaTypeFormatter());

所以默认情况下将XML,第一次格式化,但是API仍然支持JSON,如果它要求AKS(在适当的HTTP标头)。

So default will be XML, the first formatter, but the API still supports JSON if the request aks for it (with appropriate HTTP header).

最后,另一个不同的方法,就是使用自定义的<一个href=\"http://msdn.microsoft.com/en-us/library/system.net.http.formatting.icontentnegotiator%28v=vs.118%29.aspx\"相对=nofollow> IContentNegociator 。它可以让你选择最合适的 MediaTypeFormatter 对于给定的要求。

Finally, another different approach, is to use a custom IContentNegociator. It will allow you to select the most appropriate MediaTypeFormatter for a given request.

//somewhere in Web Api config
config.Services.Replace(typeof(IContentNegotiator), new MyCustomContentNegotiator());

一个例子是可用的>。

这篇关于设置默认的WebAPI格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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