There are certain times, that you had to zip some pages at the fly. After googling this for a while, I came to know about Response.Filter object, a powerful one.
This object can be used for many things. For instance, if you need to log all incoming requests / response, you could do that hooking it with the Response.Filter and write them to a fileStream or any other. If we need to log all the responses on the website level, we could add a HttpModule, and then hook with its Response.Filter Object.
So here is the trick. First we check if the client accepts deflate or gzip encoding. We first try to use deflate as it and better than gzip. Then we hook the Compression Stream with the Response.Filter object.
//Code
public void ZipResponse()
{
if (Convert.ToString(Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).Contains("deflate"))
{
Response.AddHeader("Content-Encoding", "deflate");
Response.Filter = new System.IO.Compression.DeflateStream(
Response.Filter,System.IO.Compression.CompressionMode.Compress);
}
else
if (Convert.ToString(Request.ServerVariables["HTTP_ACCEPT_ENCODING"]).contains("gzip"))
{
Response.AddHeader("Content-Encoding", "gzip");
Response.Filter = new System.IO.Compression.GZipStream(
Response.Filter, System.IO.Compression.CompressionMode.Compress);
}
}
protected void Page_Load(object sender, EventArgs e)
{
ZipResponse();
}