Search code examples
c#gziphttpmodule

Detect GZIP compression in HTTP Module


How can I detect whether or not GZIP is enabled for a particular request in my HTTP Module? I apply a filter to the output, and when it acts on gzipped content, it screws up the compression somehow, and the client browser throws an error that it can't decode the content.

    public void Init(HttpApplication context)
    {
        // if(HttpContext.Current.IsCompressed) // Check for compressed content here            

        // Set up the filter / replacement.
        context.PostReleaseRequestState += (_, __) =>
        {
            var filterStream = new ResponseFilterStream(HttpContext.Current.Response.Filter);
            filterStream.TransformString += FilterPage;
            HttpContext.Current.Response.Filter = filterStream;
        };
    }

ResponseFilterStream is a custom stream which caches all stream writes and presents the contents as an event in order to allow a method to modify the contents of the stream. It works great for modifying HTML requests (which is what I want), but I don't want it to act on gzip-compressed responses. How can I detect a gzipped response and prevent the filter stream from being hooked up to the response?


Solution

  • For a response, you can check the Encoding http header for a value of gzip or deflate

    For a request, you need to check Accept-Encoding http header for a value of gzip or deflate encoding.

    HTTP Compression