IIS提供对Chrome Postman的压缩(gzip)响应,但不提供对.NET HttpClient的响应
我已经在运行IIS 7.5的Windows Server 2008 R2机器上使用Web API 2.2创建了REST Web服务.我遇到的问题是,当我通过Google Chrome Postman应用程序发出请求时,Web服务正在返回压缩的响应(Content-Encoding:gzip).但是,当我使用.NET 4.5.1 HttpClient发出相同的请求时,服务器不会返回压缩的响应(Content-Encoding标头为空).这是我的C#代码:
I have created a REST web service using Web API 2.2 on a Windows Server 2008 R2 box running IIS 7.5. The problem that I'm having is that the web service is returning a compressed response (Content-Encoding: gzip) when I make the request through the Google Chrome Postman application. But when I make the same request using the .NET 4.5.1 HttpClient, the server does not return a compressed response (the Content-Encoding header is blank). Here is my C# code:
var handler = new HttpClientHandler();
handler.UseProxy = false;
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
handler.Credentials = CredentialCache.DefaultNetworkCredentials;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("utf-8"));
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("en-US"));
client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue { NoCache = true };
client.DefaultRequestHeaders.Connection.Add("keep-alive");
var response = await client.GetAsync("https://localhost/mywebsite");
注意:我正在使用SSL连接.我可以确认Web API Web服务正在从Postman应用程序请求和HttpClient请求中接收到Accept-Encoding: gzip
标头.实际上,两者的请求标头完全相同,只是Connection: keep-alive
标头似乎已从HttpClient请求中剥离了.有谁知道为什么该Web服务不能提供对HttpClient的压缩响应?
Note: I'm using an SSL connection. I can confirm that the Web API web service is receiving the Accept-Encoding: gzip
header from both the Postman application request and the HttpClient request. In fact, the request headers are exactly the same for both, except that the Connection: keep-alive
header seems to be stripped from the HttpClient request. Does anyone have any idea why the web service won't serve a compressed response to the HttpClient?
因此,我使用Fiddler和lo监视了HTTP流量,并发现使用HttpClient时实际上压缩了服务器响应(Postman收到的字节数是等于HttpClient接收的字节数)并发送了相应的Content-Encoding: gzip
标头!我猜想HttpClient在自动解压缩模式下会通过删除Content-Encoding: gzip
标头来尝试变得聪明.这在任何地方都有记录吗?
So, I monitored the HTTP traffic using Fiddler and lo and behold the server response was in fact compressed when using the HttpClient (the number bytes received by Postman was the same as the number of bytes received by HttpClient) and had sent the corresponding Content-Encoding: gzip
header! I guess that the HttpClient is trying to be smart by removing the Content-Encoding: gzip
header when it is in automatic decompression mode. Is this documented anywhere?