C# ASP.NET WebApi:响应GZIP压缩无效

C# ASP.NET WebApi:响应GZIP压缩无效,c#,asp.net-web-api2,compression,C#,Asp.net Web Api2,Compression,我有一个启用压缩的ASP.NET WEB API。在我的WebApiConfig.cs中,我有 config.MessageHandlers.Insert( 0, new ServerCompressionHandler( new GZipCompressor(), new DeflateCompressor() ) ); 这似乎是可行的:当我向PostMan发出请求时,我得到一个ContentEncodi

我有一个启用压缩的ASP.NET WEB API。在我的WebApiConfig.cs中,我有

config.MessageHandlers.Insert(
     0,
     new ServerCompressionHandler(
               new GZipCompressor(),
               new DeflateCompressor()
    )
);
这似乎是可行的:当我向PostMan发出请求时,我得到一个ContentEncoding=gzip的响应,ContentLength是300ko,即压缩大小

但在我的客户机(控制台程序)中使用以下C#代码:

ContentLength设置为-1,contentEncoding为空。但是,我可以在一个字符串中获得全部内容。
你能解释一下原因吗?

如果你的API在防火墙后面,它会去掉标题,结果你看不到响应,邮递员不会考虑这一点

另见:

ContentLength设置为-1,contentEncoding为空。但是,我可以在一个字符串中获得全部内容。你能解释一下为什么吗

这是设计的,请查看
HttpWebResponse
class当
Content Encoding
标题为
Gzip
Deflate
且设置了
自动压缩
标志时,它会自行显式设置这些值


似乎替换apiRequest.AutomaticDecompression=DecompressionMethods.GZip | DecompressionMethods.Deflate;通过apirest.Headers[“接受编码”]=“gzip”;作品但是为什么呢

你说它有效是什么意思? 如果您的意思是获得
ContentEncoding
ContentLength
的原始值,那么这是因为您的响应尚未解压缩

如果您想在使用
AutomaticDecompression
标志时从标题中获取原始值,则使用
headers[header key]
从响应中获取原始值(在这种情况下
apiress.headers[“Content Length”]
将是压缩数据的长度)。然而,唯一的问题是,由于引用代码中解释的某些奇怪原因,您将失去
内容编码的原始值

// Setting a response header after parsing will ruin the Common Header optimization.
// This seems like a corner case.  ContentEncoding could be added as a common header, with a special
// property allowing it to be nulled.
m_HttpResponseHeaders[HttpKnownHeaderNames.ContentEncoding] = null;

似乎替换apiRequest.AutomaticDecompression=DecompressionMethods.GZip | DecompressionMethods.Deflate;通过apirest.Headers[“接受编码”]=“gzip”;作品但是为什么呢?检查http头
HttpWebRequest
的级别非常低,它只执行您要求的操作。使用调试代理(如Fiddler)来检查Postman和您的客户端之间的差异。解释某些东西的工作方式是非常主观的,因为它就是这样工作的,尤其是在设计时。谢谢您的回答(至少有一个),但我没有防火墙。谢谢!当我说“它有效”时,我的意思是我对ContentEncoding和ContentLength有很好的值,并且我的内容没有解压缩(这是我需要的)。
// Setting a response header after parsing will ruin the Common Header optimization.
// This seems like a corner case.  ContentEncoding could be added as a common header, with a special
// property allowing it to be nulled.
m_HttpResponseHeaders[HttpKnownHeaderNames.ContentEncoding] = null;