简体   繁体   English

ASP.Net WebAPI在不同的用户代理中具有不同的内容类型

[英]ASP.Net WebAPI has different content type in different user agents

I am trying to learn ASP.Net WebAPI, and I am having a hard time figuring out what is going on. 我正在尝试学习ASP.Net WebAPI,并且很难弄清发生了什么。 I created a small application that contains an action like this: 我创建了一个包含以下操作的小型应用程序:

public IHttpActionResult Hello() 
{
    return Ok("Hi");
}

This works fine, so I look at it in the browser. 这个工作正常,所以我在浏览器中查看它。 I see: 我懂了:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hi</string>

This is using Chrome. 这是使用Chrome。 I use an extension to see the content type and it is text/xml . 我使用扩展名来查看内容类型,它是text/xml I want to check things out further so I use Postman REST Client to test it. 我想进一步检查,所以我使用Postman REST Client进行测试。 There I see: "Hi" and the content type is application/json . 在那里,我看到: "Hi" ,内容类型为application/json I am completely confused. 我完全感到困惑。 I figured that Postman was just changing the content type, but to be sure I installed another REST client but it returned application/json . 我发现Postman只是在更改内容类型,但是要确保我安装了另一个REST客户端,但它返回了application/json In Internet Explorer it attempts to download the result as a JSON file. 在Internet Explorer中,它尝试将结果下载为JSON文件。 What the heck is going on. 到底他妈发生了什么。 Is there a way I can have a universal content type? 有没有一种方法可以让我拥有通用的内容类型?

Web api can serialise responses to Xml or Json. Web api可以序列化对Xml或Json的响应。 It reads the Content-Type Http header to determine which one. 它读取Content-Type Http标头以确定哪个。 Use fiddler to examine requests from the brower. 使用提琴手检查浏览器的请求。 Postman passes application/json as the content type by default - so you get the json response. 邮递员默认将application / json作为内容类型传递-这样您会得到json响应。

You can add the following code to your WebApiConfig file to remove the XML serialiser and it will always return json. 您可以将以下代码添加到WebApiConfig文件中,以删除XML序列化器,它将始终返回json。

var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM