使用gzip压缩组件的D级

时间:2010-01-22 21:19:21

标签: asp.net http iis gzip deflate

我使用了YSlow Firefox附加组件并返回以下结果:

----------------------------------------------- ------------------------------------------
使用gzip压缩组件的D级

有3个纯文本组件应该压缩发送

* http://localhost:63808/WebSite/BemVindo/
* http://localhost:63808/WebSite/css/Global.css?...
* http://localhost:63808/WebSite/js/Global.js?...

----------------------------------------------- ------------------------------------------
所以我开始搜索并得到这段代码:

Global.asax中

Private Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)

    Dim Response As HttpResponse = HttpContext.Current.Response
    Dim AcceptEncoding As String = HttpContext.Current.Request.Headers("Accept-Encoding")

    If Not String.IsNullOrEmpty(AcceptEncoding) AndAlso AcceptEncoding.Contains("gzip") OrElse AcceptEncoding.Contains("deflate") Then
        If AcceptEncoding.Contains("deflate") Then
            Response.Filter = New System.IO.Compression.DeflateStream(Response.Filter, System.IO.Compression.CompressionMode.Compress)
            Response.AppendHeader("Content-Encoding", "deflate")
        Else
            Response.Filter = New System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress)
            Response.AppendHeader("Content-Encoding", "gzip")
        End If
    End If

    Response.AppendHeader("Vary", "Content-Encoding")

End Sub

现在我有:

使用gzip压缩组件的A级

好吧,哼哼?问题是:Application_PreRequestHandlerExecute事件是gzip / deflate请求的最佳位置吗?

2 个答案:

答案 0 :(得分:2)

不确定,但您的代码可能会导致使用Ajax的页面出现问题。以下页面显示了类似的代码,但如果检测到Ajax则取消压缩:Enabling Gzip and Deflate HTTP Compression in ASP.NET pages。我在VB中翻译了代码,但没试过。

埃里克

  Private Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
Dim app As HttpApplication = TryCast(sender, HttpApplication)
Dim acceptEncoding As String = app.Request.Headers("Accept-Encoding")
Dim prevUncompressedStream As Stream = app.Response.Filter

If Not (TypeOf app.Context.CurrentHandler Is Page OrElse app.Context.CurrentHandler.[GetType]().Name = "SyncSessionlessHandler") OrElse app.Request("HTTP_X_MICROSOFTAJAX") IsNot Nothing Then
  Return
End If

If acceptEncoding Is Nothing OrElse acceptEncoding.Length = 0 Then
  Return
End If

acceptEncoding = acceptEncoding.ToLower()

If acceptEncoding.Contains("deflate") OrElse acceptEncoding = "*" Then
  ' defalte
  app.Response.Filter = New DeflateStream(prevUncompressedStream, CompressionMode.Compress)
  app.Response.AppendHeader("Content-Encoding", "deflate")
ElseIf acceptEncoding.Contains("gzip") Then
  ' gzip
  app.Response.Filter = New GZipStream(prevUncompressedStream, CompressionMode.Compress)
  app.Response.AppendHeader("Content-Encoding", "gzip")
End If

End Sub

答案 1 :(得分:1)

是的,Application_PreRequestHandlerExecute事件是gzip / deflate请求的最佳位置。