有一个问题(或者可能是我在任何地方都没有看到合理的非常聪明的功能)DeflateStream
(GZipStream
构建DeflateStream
并继承了问题*),其中刷新可能会丢失数据。
Response.Flush()
将冲洗过滤器。解决方案是使用一个知道压缩和底层接收器的包装器,并且只刷新后者:
public enum CompressionType
{
Deflate,
GZip
}
/// <summary>
/// Provides GZip or Deflate compression, with further handling for the fact that
/// .NETs GZip and Deflate filters don't play nicely with chunked encoding (when
/// Response.Flush() is called or buffering is off.
/// </summary>
public class WebCompressionFilter : Stream
{
private Stream _compSink;
private Stream _finalSink;
public WebCompressionFilter(Stream stm, CompressionType comp)
{
switch(comp)
{
case CompressionType.Deflate:
_compSink = new DeflateStream((_finalSink = stm), CompressionMode.Compress);
break;
case CompressionType.GZip:
_compSink = new GZipStream((_finalSink = stm), CompressionMode.Compress);
break;
}
}
public override bool CanRead
{
get
{
return false;
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override bool CanWrite
{
get
{
return true;
}
}
public override long Length
{
get
{
throw new NotSupportedException();
}
}
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
public override void Flush()
{
//We do not flush the compression stream. At best this does nothing, at worse it
//loses a few bytes. We do however flush the underlying stream to send bytes down the
//wire.
_finalSink.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
_compSink.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
_compSink.WriteByte(value);
}
public override void Close()
{
_compSink.Close();
_finalSink.Close();
base.Close();
}
protected override void Dispose(bool disposing)
{
if(disposing)
{
_compSink.Dispose();
_finalSink.Dispose();
}
base.Dispose(disposing);
}
}
还值得注意的是,大多数支持 gzip-encoding 的用户代理也支持 deflate-encoding。虽然 deflate 对大小的改进可以忽略不计(字面意思是几个字节),但某些架构上的一些库对 deflate 的处理要好得多(这适用于压缩和解压缩),因此始终值得使用 deflate 而不是使用 HTTP 压缩的 gzip。