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?
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?