Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Shada 55 posts 137 karma points
    Feb 01, 2016 @ 16:32
    Shada
    0

    custom GZip compression in ASP.NET MVC5

    Running IIS without default compression. I'm trying to implement a custom Http Module, what I actually want is to implement gzip compression.

     public class HtmlCompress : IHttpModule
        {
            public HtmlCompress()
            {
            }
    
            public void Dispose()
            {
            }
    
            public void Init(HttpApplication context)
            {
                context.BeginRequest +=
                    (new EventHandler(this.Application_BeginRequest));
    
            }
    
            private void Application_BeginRequest(object sender, EventArgs e)
            {
                HttpContext context = HttpContext.Current;
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
                HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
        }
    

    And add ref to

    <add name="HtmlCompress" type="HtmlCompress"/>
    

    But it's not working.

    Umbraco 7.2.6

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 01, 2016 @ 17:16
    Alex Skrypnyk
    0

    Hi Shada,

    We are using another approach. BasePage.cs:

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
    
            GZipHelper.GZipEncodePage();
        }
    

    GZipHelper.cs:

    public class GZipHelper
    {
        /// <summary>
        /// Sets up the current page or handler to use GZip through a Response.Filter
        /// IMPORTANT: 
        /// You have to call this method before any output is generated!
        /// </summary>
        public static void GZipEncodePage()
        {
            var response = HttpContext.Current.Response;
    
            if (IsGZipSupported())
            {
                var acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
                if (acceptEncoding.Contains("deflate"))
                {
                    response.Filter = new DeflateStream(response.Filter,
                                               CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "deflate");
                }
                else
                {
                    response.Filter = new GZipStream(response.Filter,
                                              CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "gzip");
                }
            }
    
            // Allow proxy servers to cache encoded and unencoded versions separately
            response.AppendHeader("Vary", "Content-Encoding");
        }
    
        /// <summary>
        /// Determines if GZip is supported
        /// </summary>
        /// <returns></returns>
        public static bool IsGZipSupported()
        {
            string acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
    
            if (string.IsNullOrEmpty(acceptEncoding)) return false;
            if (!acceptEncoding.Contains("gzip") && !acceptEncoding.Contains("deflate")) return false;
    
            var isPartial = HttpContext.Current.Request.Headers["x-microsoftajax"];
    
            //Just checking to see if this is a partial page update
            //See http://bit.ly/GlHfD for more info.
    
            return System.String.Compare("Delta=true", isPartial, System.StringComparison.OrdinalIgnoreCase) != 0;
        }
    
        public static void CompressFile(string inputFilePath, string resultFilePath)
        {
            FileStream sourceFileStream = File.OpenRead(inputFilePath);
            FileStream destFileStream = File.Create(resultFilePath);
    
            GZipStream compressingStream = new GZipStream(destFileStream,
                CompressionMode.Compress);
    
            byte[] bytes = new byte[2048];
            int bytesRead;
            while ((bytesRead = sourceFileStream.Read(bytes, 0, bytes.Length)) != 0)
            {
                compressingStream.Write(bytes, 0, bytesRead);
            }
    
            sourceFileStream.Close();
            compressingStream.Close();
            destFileStream.Close();
        }
    }
    

    Thanks,

    Alex

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 01, 2016 @ 17:46
    Alex Skrypnyk
    0

    Are you using asp.net ?

  • Shada 55 posts 137 karma points
    Feb 01, 2016 @ 18:07
    Shada
    0

    Alex Skrypnyk, I use ASP.Net MVC5

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 01, 2016 @ 18:08
    Alex Skrypnyk
    0

    Shada, you can configure compression through your web.config file as follows:

    <system.webServer>
        <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    </system.webServer>
    

    Thanks,

    Alex

  • Shada 55 posts 137 karma points
    Feb 01, 2016 @ 18:19
    Shada
    0

    Alex Skrypnyk, unfortunately it did not help :(

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 01, 2016 @ 18:33
    Alex Skrypnyk
    0

    Shada, what IIS do you use ?

    How do you test gzip response or not ?

    Best,

    Alex

  • Shada 55 posts 137 karma points
    Feb 01, 2016 @ 19:32
    Shada
    0

    I see the response size and headers:

    Cache-Control:private
    Content-Type:text/html; charset=utf-8
    Date:Mon, 01 Feb 2016 19:30:30 GMT
    Transfer-Encoding:chunked
    

    version iis 7

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 01, 2016 @ 21:47
    Alex Skrypnyk
    0

    Shada, try this config section:

    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
      <dynamicTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="application/atom+xml" enabled="true" />
        <add mimeType="application/xaml+xml" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>
    
    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    

  • Shada 55 posts 137 karma points
    Feb 02, 2016 @ 05:41
    Shada
    0

    Nothing has changed

    Edit:

    • I checked the existence of gzip.dll
    • I checked if my application is running in IIS 7.0 Integrated mode
    • I tested the code in the debugger in HtmlCompress
  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 02, 2016 @ 11:27
    Alex Skrypnyk
    0

    Shada, it's really really strange. I think this:

    <add name="HtmlCompress" type="HtmlCompress"/>
    

    Is useless key.

    Thanks

  • Shada 55 posts 137 karma points
    Feb 02, 2016 @ 12:47
    Shada
    0

    Why? This adds a module in the iis 7

  • Shada 55 posts 137 karma points
    Feb 02, 2016 @ 12:51
    Shada
    0

    Now I try write "ActionFilter" for compressing data in my SurfaceController:

    using System.Web;
    using System.Web.Mvc;
    
    public class CompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(FilterExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;
    
            string acceptEncoding = request.Headers["Accept-Encoding"];
    
            if (string.IsNullOrEmpty(acceptEncoding)) return;
    
            acceptEncoding = acceptEncoding.ToUpperInvariant();
    
            HttpResponseBase response = filterContext.HttpContext.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);
            }
        }
    } 
    

    Use:

      [CompressFilter]
            public ActionResult FindOrganizations()
    

    But the compression is still not happening! Below is response header in chrome.

    Cache-Control:private
    Content-Type:text/html; charset=utf-8
    Date:Tue, 02 Feb 2016 12:45:52 GMT
    Transfer-Encoding:chunked
    X-MiniProfiler-Ids:["7f917847-6163-46b3-8777-85842e7288d8","66fb528e-5733-4df4-bed3-ee45dec04807","054cc610-f702-44cc-a73d-2d8f96cd9b6b","2bc268f4-b9ff-442a-b1e3-c8669eac3684"]
    
  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 02, 2016 @ 12:52
    Alex Skrypnyk
    0

    Shada, what browser are you using ? maybe problem with browser ?

  • Shada 55 posts 137 karma points
    Feb 02, 2016 @ 13:21
    Shada
    0

    Alex Skrypnyk, I've tested in Chrome, Firefox and Fiddler

  • Alex Skrypnyk 6132 posts 23951 karma points MVP 7x admin c-trib
    Feb 02, 2016 @ 15:06
    Alex Skrypnyk
    0

    Shada, usually it's just config changes. Do you have some ideas what is the problem ?

  • Shada 55 posts 137 karma points
    Feb 03, 2016 @ 08:23
    Shada
    0

    Alex Skrypnyk, Maybe it has something to do with the CPU load. Although it is usually about 60%.

Please Sign in or register to post replies

Write your reply to:

Draft