Gzip example in Global.asax


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <%@ Application Language="C#" %>
  2. <%@ Import Namespace="System.IO" %>
  3. <%@ Import Namespace="System.IO.Compression" %>
  4.  
  5. <script runat="server">
  6. void Application_PreRequestHandlerExecute(object sender, EventArgs e)
  7. {
  8. HttpApplication app = sender as HttpApplication;
  9. string acceptEncoding = app.Request.Headers["Accept-Encoding"];
  10. Stream prevUncompressedStream = app.Response.Filter;
  11.  
  12. if (!(app.Context.CurrentHandler is Page ||
  13. app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
  14. app.Request["HTTP_X_MICROSOFTAJAX"] != null)
  15. return;
  16.  
  17. if (acceptEncoding == null || acceptEncoding.Length == 0)
  18. return;
  19.  
  20. acceptEncoding = acceptEncoding.ToLower();
  21.  
  22. if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
  23. {
  24. // defalte
  25. app.Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
  26. app.Response.AppendHeader("Content-Encoding", "deflate");
  27. }
  28. else if (acceptEncoding.Contains("gzip"))
  29. {
  30. // gzip
  31. app.Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
  32. app.Response.AppendHeader("Content-Encoding", "gzip");
  33. }
  34. }
  35. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.