开发者

How to compress JavaScript and CSS using gzip compression in Asp .Net 3.5 web application?

开发者 https://www.devze.com 2022-12-15 00:10 出处:网络
How to compress JavaScript and CSS using gzip compression in Asp .Net 3.5 web application? Gzip compression results error in CSS menu and validat开发者_JAVA百科ors scripts.Why don\'t you use HttpCompr

How to compress JavaScript and CSS using gzip compression in Asp .Net 3.5 web application? Gzip compression results error in CSS menu and validat开发者_JAVA百科ors scripts.


Why don't you use HttpCompression? That would enable you to compress all static content including javascript and CSS files.

HttpCompression IIS 6

HttpCompression IIS 7


(I've been using this technique for quite a while - hence the vb.net code!)

Although compression is not supported by IIS 6.0, most browsers support basic gzip compression and they notify the server of this ability by sending a header in each request. The following piece of code shows how to use the System.IO.Compression namespace to add a filter to the output stream that compresses the output whilst checking and setting the correct headers.

 context.Response.Clear()
 context.Response.Buffer = True

 context.Response.AddHeader("content-disposition", String.Format( "attachment;filename={0}", fileName))
 context.Response.ContentEncoding = Encoding.UTF8

 context.Response.Cache.SetCacheability(HttpCacheability.Private)

 'Compress the output as it may be very large
 'When flushing or closing+ending the stream, the compression filter does not have a chance to write the compression footer
 'Therefore, make sure the compression filter stream is closed before flushing
 AddCompression(context)

 context.Response.ContentType = "application/vnd.ms-excel" 'This example was an excel doc

 'Write to response
 context.Response.Write(your-data-here)

 'context.Response.Flush() 'Do not flush if using compression
 'context.Response.Close()
 context.Response.End()

The AddCompression method checks the appropriate headers and adds a compression filter stream to the output:

'Add compression to the response stream
Public Sub AddCompression(ByVal context As HttpContext)

    Dim acceptEncoding As String = context.Request.Headers("Accept-Encoding")
    If acceptEncoding Is Nothing OrElse acceptEncoding.Length = 0 Then Return

    'Convert to lower to check
    acceptEncoding = acceptEncoding.ToLower

    'Gzip or Compress compression
    'Compress compression is quicker and performs better compression so try that first
    If (acceptEncoding.Contains("deflate")) Then

        context.Response.Filter = New DeflateStream(context.Response.Filter, CompressionMode.Compress)
        context.Response.AppendHeader("Content-Encoding", "deflate")

    ElseIf acceptEncoding.Contains("gzip") Then

        context.Response.Filter = New GZipStream(context.Response.Filter, CompressionMode.Compress)
        context.Response.AppendHeader("Content-Encoding", "gzip")

    End If

End Sub


add the below code to Global.asax and put it into your root directory.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.IO.Compression" %>

 <script runat="server">
 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 is 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 == "*")
{
    // defalte
    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");
}
}
</script>


Download gzip compression sample code and add it to your Global.asax file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号