Thứ Năm, 14 tháng 8, 2014

Compressing HTML output in ASP.Net / ASP.Net MVC

Most modern browsers have capability to get output from webservers in compressed form. This reduces number of bytes to be transferred and thus making transmission faster. Browsers that support this functionality specify supported compression type as value of “Accept-Encoding” attribute for example “Accept-Encoding: gzip, deflate”. gzip and deflate being two most commonly supported compression types. This can be configured at web server level but if you want to do have a lot of control over we server configuration like in shared hosting environment you can implement IHttpModule and set it up for your application as follows - 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO.Compression;
namespace MyPackage
{
    public class HttpCompressionModule : IHttpModule
    {
        #region IHttpModule Members
        void IHttpModule.Dispose()
        {            
        }
        void IHttpModule.Init(HttpApplication context)
        {
            context.PostAcquireRequestState += new EventHandler(context_PostAcquireRequestState);
            context.EndRequest += new EventHandler(context_EndRequest);
        }
        void context_EndRequest(object sender, EventArgs e)
        {
            HttpApplication context = sender as HttpApplication;
            context.PostAcquireRequestState -= new EventHandler(context_PostAcquireRequestState);
            context.EndRequest -= new EventHandler(context_EndRequest);
        }
        void context_PostAcquireRequestState(object sender, EventArgs e)
        {
            this.RegisterCompressFilter();    
        }
        private void RegisterCompressFilter()
        {
            HttpContext context = HttpContext.Current;
            if (context.Handler is StaticFileHandler 
                || context.Handler is DefaultHttpHandler) return;
            HttpRequest request = context.Request;            
            string acceptEncoding = request.Headers[“Accept-Encoding”];
            if (string.IsNullOrEmpty(acceptEncoding)) return;
            //if (request.FilePath.EndsWith(“.ashx”)) return;
            if (request.FilePath.Contains(“.”))
            {
                return;
            }
            acceptEncoding = acceptEncoding.ToUpperInvariant();
            HttpResponse response = HttpContext.Current.Response;
            if (acceptEncoding.Contains(“GZIP”))
            {
                response.AppendHeader(“Content-encoding”, “gzip”);
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains(“DEFLATE”))
            {
                response.AppendHeader(“Content-encoding”, “deflate”);
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
        #endregion
    }
}

0 nhận xét:

Đăng nhận xét