MVC 3 compression filter causing garbled output

前端 未结 4 1708
囚心锁ツ
囚心锁ツ 2020-12-28 08:24

So, I have a custom attribute called CompressAttribute which is set up as a global filter in global.asax. It uses reflection to examine the return type of the current action

4条回答
  •  暖寄归人
    2020-12-28 09:25

    The accepted answer won't work if anything has been already written to the output.

    Instead of disposing the filter you can make sure the headers are being persisted in place:

     protected void Application_PreSendRequestHeaders()
    {
        // ensure that if GZip/Deflate Encoding is applied that headers are set
        // also works when error occurs if filters are still active
        HttpResponse response = HttpContext.Current.Response;
        if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip")
            response.AppendHeader("Content-encoding", "gzip");
        else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate")
            response.AppendHeader("Content-encoding", "deflate");
    }
    

提交回复
热议问题