"Invalid use of response filter" when compressing response from an IHttpHandler

2.2k views Asked by At

I have an IHttpHandler returning a file. When the response stream is compressed, either automatically using Telerik RadCompression or by explicitly setting a filter using

context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);

the response returned to the browser is correct but at the end of the response is some HTML. The HTML contains the exception:

[HttpException (0x80004005): Invalid use of response filter]
   System.Web.HttpResponseStreamFilterSink.VerifyState() +3928894
   System.Web.HttpResponseStreamFilterSink.Write(Byte[] buffer, Int32 offset, Int32 count) +28
   System.IO.Compression.DeflateStream.Dispose(Boolean disposing) +363
   System.IO.Stream.Close() +28
   System.IO.Compression.GZipStream.Dispose(Boolean disposing) +63
   System.IO.Stream.Close() +28
   System.IO.Compression.DeflateStream.Dispose(Boolean disposing) +595
   System.IO.Stream.Close() +28
   System.IO.Compression.GZipStream.Dispose(Boolean disposing) +63
   System.IO.Stream.Close() +28
   System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +754
   System.Web.HttpResponse.FilterOutput() +121
   System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +174

If I make sure the response is NOT compressed, the response contains no exception.

What's up with that?

1

There are 1 answers

0
Lobstrosity On

Make sure you're not preventing buffering. Apparently, to compress the response, you have to allow it to be buffered.

I.e., one of the following two lines needs to be removed:

context.Response.BufferOutput = false;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);