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

查看:41
本文介绍了设置默认的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 be 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.

我可以通过从Formatters集合中删除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,但如果请求(带有适当的HTTP标头)要求,API仍支持JSON.

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

最后,另一种不同的方法是使用自定义

Finally, another different approach, is to use a custom IContentNegotiator. 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天全站免登陆