gzip压缩与动作过滤器无法正常工作

时间:2012-03-25 16:33:38

标签: asp.net-mvc compression gzip action-filter

我正在使用一个actionfilter来压缩我对来自控制器内部动作的响应

这是我的动作过滤器:

Public Class CompressAttribute 
        Inherits ActionFilterAttribute 
        Implements IActionFilter 
        Public Overrides Sub OnActionExecuting(filterContext As ActionExecutingContext) 
            Dim request As HttpRequestBase = filterContext.HttpContext.Request 

            Dim acceptEncoding As String = request.Headers("Accept-Encoding") 

            If String.IsNullOrEmpty(acceptEncoding) Then 
                Return 
            End If 
            acceptEncoding = acceptEncoding.ToUpperInvariant() 

            Dim response As HttpResponseBase = filterContext.HttpContext.Response 
            If acceptEncoding.Contains("DEFLATE") Then 

                response.AppendHeader("Content-encoding", "deflate") 

                response.AppendHeader("Vary", "Accept-Encoding") 
                response.Filter = New WebCompressionFilter(response.Filter, CompressionMode.Compress) 

            ElseIf acceptEncoding.Contains("GZIP") Then 
               response.AppendHeader("Content-encoding", "gzip") 
                response.AppendHeader("Vary", "Accept-Encoding") 
                response.Filter = New WebCompressionFilter(response.Filter, CompressionMode.Compress) 
            End If 
        End Sub 
    End Class 

我将它应用于我的控制者内部的行动。

问题是它在开发环境中的桌面上运行得很好但在我的实时服务器上(在共享主机中)它没有gzip编码。

相反,它会进行分块传输编码....

为什么?

这是我的回答:

开发环境:

HTTP/1.1 200 OK

Server: ASP.NET Development Server/10.0.0.0

Date: Sun, 25 Mar 2012 04:12:29 GMT

X-AspNet-Version: 4.0.30319

p3p: CP=\'NOI ADM DEV PSAi COM NAV OUR OTR STP IND DEM\'

X-AspNetMvc-Version: 3.0

Content-Encoding: gzip

Cache-Control: private

Content-Type: text/html; charset=utf-8

Content-Length: 13411

Connection: Close

直播服务器:

HTTP/1.1 200 OK

Cache-Control: private

Content-Type: text/html; charset=utf-8

Server: Microsoft-IIS/7.5

p3p: CP=\'NOI ADM DEV PSAi COM NAV OUR OTR STP IND DEM\'

X-AspNetMvc-Version: 3.0

X-AspNet-Version: 4.0.30319

X-Powered-By: ASP.NET

Date: Sun, 25 Mar 2012 04:13:09 GMT

Transfer-Encoding: chunked

X-OSSProxy: OSSProxy 1.3.331.322 (Build 331.322 Win32 en-us)(Oct 11 2011 17:53:42)

Connection: close

1 个答案:

答案 0 :(得分:0)

您是否有任何理由在自己的代码中手动执行此操作? IIS中已存在此功能:

确保您在计算机上有installed动态内容压缩(链接中的项目符号5)和enabled it in IIS。完成这些步骤后,我从未遇到任何问题。一旦你这样做,也不再需要你的属性,IIS将隐式处理静态和动态内容。维护更少的代码总是一件好事!