본문으로 바로가기

IHttpModule을 이용한 Gzip 적용

category .NET/ASP.NET 2015. 5. 7. 10:51
//C# 코드
using System;
using System.IO;
using System.IO.Compression;
using System.Web;


/// 
/// ContentManager의 요약 설명입니다.
/// 
/// 
public class HttpCompressionModule : IHttpModule
{
    HttpApplication app = null;
    public HttpCompressionModule()
    {
    }
    public void Dispose()
    {
        if (app != null)
        {
            if (IsGZipSupported())
            {
                app.BeginRequest -= new EventHandler(context_BeginRequest);
                app = null;
            }
        }
    }
    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(context_BeginRequest);
        context.EndRequest += new EventHandler(context_EndRequest);
    }

    void context_EndRequest(object sender, EventArgs e)
    {
        
    }

    void context_BeginRequest(object sender, EventArgs e)
    {
        if (IsGZipSupported())
        {
            app = sender as HttpApplication;
            string file = app.Server.MapPath(app.Request.FilePath);//파일 경로
            FileInfo fileInfo = new FileInfo(file);
            string encodings = app.Request.Headers.Get("Accept-Encoding");
            if (encodings == null)
                return;
            
            Stream baseStream = app.Response.Filter;
            encodings = encodings.ToLower();
            if (fileInfo.Exists && fileInfo.Length > 1024)//1K 용량 설정
            {
                if (encodings.Contains("gzip"))
                {
                    app.Response.Filter = new GZipStream(baseStream,
                        CompressionMode.Compress);
                    app.Response.AppendHeader("Content-Encoding", "gzip");
                    app.Context.Trace.Warn("GZIP compression on");
                }
                else if (encodings.Contains("deflate"))
                {
                    app.Response.Filter = new DeflateStream(baseStream,
                        CompressionMode.Compress);
                    app.Response.AppendHeader("Content-Encoding", "deflate");
                    app.Context.Trace.Warn("Deflate compression on");
                }
            }
        }
    }

    /// GZip을 지원하는 브라우져인지를 확인한다.
    private bool IsGZipSupported()
    {
        bool result = false;
        bool IsAjaxCall = true; 
        try
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            IsAjaxCall = HttpContext.Current.Request.Headers["x-microsoftajax"] != null;
            IsAjaxCall = HttpContext.Current.Request.Headers["If-Modified-Since"] != null;

            if (IsAjaxCall) return false;
            if (HttpContext.Current.Request.Path.IndexOf(".axd") > 0)
                return false;
            if (!string.IsNullOrEmpty(AcceptEncoding) &&
                 AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))
            {
                result = true;
            }
        }
        catch { }
        return result;
    }
}




      





      
    

<참고> https://msdn.microsoft.com/en-us/library/vstudio/ms227673(v=vs.100).aspx