我有一个.NET Core 2.0控制台应用程序执行GET请求。
似乎已发布的版本不会在测试计算机上发送用于压缩的Accept-Encoding
标头,但可以在我的本地计算机上运行。
我找不到任何会导致压缩失败的其他预先请求。两者都运行.NET Core 2.1.4 SDK。
我通过在两种环境中运行dotnet Console.dll
来测试控制台应用程序。
dotnet Console.dll
。验证Fiddler中存在的标题。dotnet Console.dll
并使用Fiddler验证服务器上缺少标头。我试过HttpClient
和RestSharp
,我很困惑。
转到与请求标头相呼应的页面的概念证明:
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
};
using (var client = new HttpClient(handler))
{
response = client.GetStringAsync("http://scooterlabs.com/echo").Result;
}
本地环境(Win10)
GET http://scooterlabs.com/echo HTTP/1.1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Host: scooterlabs.com
服务器(AWS上的Win2008 R2)
GET http://scooterlabs.com/echo HTTP/1.1
Connection: Keep-Alive
Host: scooterlabs.com
我最好的猜测是因为WinHttp库,在Windows 8.1+之前的Windows版本上,Windows上的HttpClient默认使用Windows上的does not support gzip \ deflate。支持时 - WinHttp还将设置Accept-Encoding标头。因此,在Windows Server 2008上.NET通过WinHttp路由请求时 - 它会设置此选项并被忽略,或者检查是否支持此选项,如果不支持 - 只是不设置它。
如果您手动设置此标头(如client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
) - 仍会忽略选项但标头通过,服务器返回压缩响应。如果支持 - WinHttp将解压缩该响应并删除Content-Encoding标头,因此响应将解压缩到.NET。如果不支持 - 响应将到达压缩状态,如果设置AutomaticDecompression
,.NET本身将解压缩它。
总而言之 - 在8.1之前的Windows版本上,似乎你需要设置AutomaticDecompression
和相关的Accept-Encoding
头文件,以便按预期工作。
不是答案,尽管我试图在Azure的Win Server 2008 R2上使用不同的Echo服务器(.NET Core SDK 2.1.4)重现这一点
// http://scooterlabs.com/echo output
[headers] => Array
(
[Connection] => Keep-Alive
[Host] => scooterlabs.com
)
// http://httpbin.org/headers output
{
"headers": {
"Connection": "close",
"Host": "httpbin.org"
}
}
// https://postman-echo.com/headers output
{
"headers": {
"host": "postman-echo.com",
"x-forwarded-port": "443",
"x-forwarded-proto": "https"
}
}
在Win10上确实我也有这些标题。
// http://scooterlabs.com/echo output
[headers] => Array
(
[Connection] => Keep-Alive
[Accept-Encoding] => gzip, deflate
[Host] => scooterlabs.com
)
// http://httpbin.org/headers output
{
"headers": {
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org"
}
}
// https://postman-echo.com/headers output
{
"headers": {
"host": "postman-echo.com",
"accept-encoding": "gzip, deflate",
"x-forwarded-port": "443",
"x-forwarded-proto": "https"
}
}
这让我觉得WS 2008 R2真的不支持HttpClient
的Accept-Encoding
标题。
基于Ivan和Evk的答案,看来这是一个特定于旧版本Windows(早于Win8.1)的问题。以下是如何在旧版Windows上解决并成功处理压缩的方法。
var handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
response = client.GetStringAsync("http://scooterlabs.com/echo").Result;
}
除了标题之外,还必须设置AutomaticDecompression
,否则您将获得压缩的有效负载。