How to implement GZip compression in ASP.NET?

后端 未结 9 826
后悔当初
后悔当初 2020-11-27 10:21

I am trying to implement GZip compression for my asp.net page (including my CSS and JS files). I tried the following code, but it only compresses my .aspx page (found it fro

相关标签:
9条回答
  • 2020-11-27 10:39

    Here is the solution for css and javascript files. Add the following code to inside your web.config file:

      <httpCompression>
        <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
        <dynamicTypes>
          <add mimeType="text/*" enabled="true"/>
          <add mimeType="message/*" enabled="true"/>
          <add mimeType="application/javascript" enabled="true"/>
          <add mimeType="*/*" enabled="false"/>
        </dynamicTypes>
        <staticTypes>
          <add mimeType="text/*" enabled="true"/>
          <add mimeType="message/*" enabled="true"/>
          <add mimeType="application/javascript" enabled="true"/>
          <add mimeType="*/*" enabled="false"/>
        </staticTypes>
      </httpCompression>
      <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
    

    Credit: How to GZip on ASP.NET and GoDaddy

    0 讨论(0)
  • 2020-11-27 10:50

    Add .aspx extension to .css or .js file. Use <%@ Page ContentType="text/css" %> or javascript within the file to serve it with correct MIME type. & use URL Rewrite to hide this from the user agent browsers. The content-encoding response header is appended gzip to convey that gzip is the method used to perform compression. Vary response header's set to Accept-Encoding so all caches know which page (compressed or uncompressed) should be served depends on request's Accept-Encoding header. I've elaborated on this at https://stackoverflow.com/a/14509007/1624169

    0 讨论(0)
  • 2020-11-27 10:51

    this may be useful for you try it out, this accepts deflate and gzip compression.

        void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;
            string acceptEncoding = app.Request.Headers["Accept-Encoding"];
            Stream prevUncompressedStream = app.Response.Filter;
    
            if (app.Context.CurrentHandler == null)
                return;
    
            if (!(app.Context.CurrentHandler is System.Web.UI.Page ||
                app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
                app.Request["HTTP_X_MICROSOFTAJAX"] != null)
                return;
    
            if (acceptEncoding == null || acceptEncoding.Length == 0)
                return;
    
            acceptEncoding = acceptEncoding.ToLower();
    
            if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
            {
                // deflate
                app.Response.Filter = new DeflateStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
            else if (acceptEncoding.Contains("gzip"))
            {
                // gzip
                app.Response.Filter = new GZipStream(prevUncompressedStream,
                    CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");
            }
        } 
    
    0 讨论(0)
  • 2020-11-27 10:51

    Either do it with the web.config file

    <system.webServer>
        <httpCompression>
            <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
            <dynamicTypes>
                <add mimeType="text/*" enabled="true"/>
                <add mimeType="message/*" enabled="true"/>
                <add mimeType="application/javascript" enabled="true"/>
                <add mimeType="*/*" enabled="false"/>
            </dynamicTypes>
            <staticTypes>
                <add mimeType="text/*" enabled="true"/>
                <add mimeType="message/*" enabled="true"/>
                <add mimeType="application/javascript" enabled="true"/>
                <add mimeType="*/*" enabled="false"/>
            </staticTypes>
        </httpCompression>
        <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
    </system.webServer>
    

    Or you can do it through IIS. For compressing JS & CSS files you actually have to handle that at the IIS level, since these files are rendered directly without the ASP.NET runtime.

    You could make a JSX & CSSX extension mapping in IIS to the aspnet_isapi.dll and then take advantage of your zip code, but IIS is likely to do a better job of this for you.

    The content-encoding header tells the browser that it needs to unzip the content before rendering. Some browsers are smart enough to figure this out anyway, based on the shape of the content, but it's better to just tell it.

    The Accept-encoding cache setting is there so that a cached version of the gzipped content won't be sent to a browser that requested only text/html.

    0 讨论(0)
  • 2020-11-27 10:53

    The reason it's only compressing your ASPX file is that the code you have written is only embedded in the ASPX file. An ASPX file is a separate request from any linked content it contains. So if you have an ASPX page that contains:

    <img src="www.example.com\exampleimg.jpg" alt="example" />
    

    This would amount to 2 requests (DNS lookups aside) from your browser to the resources:

    1. for the aspx page and
    2. for the image contained by the aspx page.

    Each request has it own response steam. The code you have posted is attaching to the ASPX response stream only, which is why only your ASPX page is being compressed. Lines 1 & 2 of your posted code are essentially taking over the normal response stream of the page and injecting some "middle man" code that in this case eats and compresses the normal output stream with a GZip stream and sends that down the wire instead.

    Lines 3 & 4 are setting up the response headers. All http requests and responses have headers that are sent prior to the content. These set up the request/response so that the server and client know what is being sent and how.

    In this case Line 3 is informing the client browser that the response stream is compressed via gzip and therefore needs to be de-compressed by the client browser prior to display.

    And Line 4 is simply turning on the Accept-Encoding header of the response. This would otherwise have been absent from the response.

    There are pluggable modules you can write/obtain that allow you to compress a multitide of other MIME type such as *.js and *.css but you're better off just using the built in compression functionality of IIS.

    You haven't said which verson of IIS you are using but if it were IIS 7.0, it would require that you include something like the following into the <system.webserver> section of you web.config file:

    <httpCompression> 
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" /> 
     <staticTypes>
             <add mimeType="text/*" enabled="true" />
          </staticTypes>
    </httpCompression> 
    <urlCompression doStaticCompression="true" /> 
    

    ..

    Richard

    0 讨论(0)
  • 2020-11-27 10:54

    You can just add the following to your web.config file within the <system.webServer> element:

    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    

    NOTE: If you are using an older version of IIS (less than v7.5), you may want to set doDynamicCompression to false because the process was CPU intensive. These issues were cleared up in IIS 7.5.

    Reference: https://docs.microsoft.com/en-us/iis/configuration/system.webserver/urlcompression

    0 讨论(0)
提交回复
热议问题