asp.net compression in a hurry

2008-01-11 @ 17:32#

recently, i made a post that showed how to add streaming compression support to your ASP.NET projects for any type of dynamic content. turns out this was a bit more than i needed in some cases. sometimes, i have a quick one-off ASHX file that i need to add compression to, but don't want to write a Response filter. in that case, you can just add the following method to your code and make the call before you do your first Response.Write statement:

private void SetCompression(HttpContext ctx)
{
    // call this method before your first Response.Write: SetCompression(HttpContext.Current);
    string accept = (ctx.Request.Headers["Accept-encoding"] != null ? ctx.Request.Headers["Accept-encoding"] : string.Empty);

    if (accept.Contains("gzip"))
    {
        ctx.Response.Filter = new GZipStream(ctx.Response.Filter, CompressionMode.Compress);
        ctx.Response.AppendHeader("Content-Encoding", "gzip");
        return;
    }

    if (accept.Contains("deflate"))
    {
        ctx.Response.Filter = new DeflateStream(ctx.Response.Filter, CompressionMode.Compress);
        ctx.Response.AppendHeader("Content-Encoding", "deflate");
        return;
    }

    // if no match found
    return;
}

code