IIS serves a compressed (gzip) response to Chrome Postman but not to .NET HttpClient

岁酱吖の 提交于 2019-12-13 05:25:35

问题


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");

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?


回答1:


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?



来源:https://stackoverflow.com/questions/28837600/iis-serves-a-compressed-gzip-response-to-chrome-postman-but-not-to-net-httpcl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!