How to compress response in

In this post I will show you how to compress http response in for improving performance. Before going into details let's create a simple website with single page Default.aspx and add following code into it Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <form id="form1" runat="server">
        <asp:GridView ID="grdPerson" runat="server">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            grdPerson.DataSource = Person.Persons;

public class Person
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Phone { get; set; }
    public string Email { get; set; }
    public static List<Person> Persons
            return new List<Person>()
                    new Person(){FirstName="Santosh",LastName="Singh",Phone=1213123,Email=""},
                    new Person(){FirstName="Ashok",LastName="Singh",Phone=1213123,Email=""},
                    new Person(){FirstName="Bill",LastName="Gates",Phone=1213123,Email=""},

    public override string ToString()
        return string.Format(@"FirstName {0} & LastName {1} Phone {2} Email {3}", this.FirstName, this.LastName, this.Phone, this.Email);
Now,press F5 and see the response result in FireBug.You will see the response result something like below
Note down the Content-Length size(in my case is 1720) Let's compress the response.For this right click on website ,and add Global.asax file.Inside this file add a method named
void Application_BeginRequest(object sender, EventArgs e)

Inside it paste the following code and see the result in FireBug
 void Application_BeginRequest(object sender, EventArgs e)
        HttpContext incoming = HttpContext.Current;
        string oldpath = incoming.Request.Path.ToLower();
        incoming.Response.Filter = new System.IO.Compression.GZipStream(incoming.Response.Filter, System.IO.Compression.CompressionMode.Compress);
        HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
        HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

Check the Content-Length property after compression. Note:For compress/decompression I am using .net framework class GZipStream

No comments:

Post a Comment