如何解压缩应用程序错误的响应?

时间:2011-11-08 20:54:17

标签: c# compression gzip response

我遇到一个问题,当我的Web应用程序中发生服务器错误时,我看到gzip的服务器错误呈现在屏幕上,而不是实际的错误消息。我试图通过在Application_Error上调用GZIP Decompress来解决这个问题。

我无法解压缩HttpContext.Current.Response流,因为它无法读取。也就是说,CanRead是假的,但CanWrite是真的。这让我相信我做的事情完全不正确,所以我也愿意接受建议。

protected void Application_Error(object sender, EventArgs e)
{
    if (HttpContext.Current.Error != null)
    {
        this.GetType().GetLogger().Error(HttpContext.Current.Error);
    }

    CompressionManager.Decompress();
}

public static void Decompress()
{
    //Determine types of compression possible.
    string acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
    if (string.IsNullOrEmpty(acceptEncoding)) return;

    //Make sure the stream is actually compressed.
    HttpResponse response = HttpContext.Current.Response;
    bool compressed = response.Headers.AllKeys.Contains("Content-encoding");
    if (!compressed) return;

    acceptEncoding = acceptEncoding.ToUpperInvariant();

    using ( MemoryStream memStream = new MemoryStream() )
    {
        byte[] buffer = new byte[1024];
        int byteCount;
        do
        {
            byteCount = response.Read(buffer, 0, buffer.Length);
            memStream.Write(buffer, 0, byteCount);
        } while (byteCount > 0);

        // If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning.
        memStream.Seek(0, SeekOrigin.Begin);

        if (acceptEncoding.Contains("GZIP"))
        {
            using (GZipStream decompress = new GZipStream(memStream, CompressionMode.Decompress))
            {
                decompress.CopyTo(response.Filter);
            }
        }
        else if (acceptEncoding.Contains("DEFLATE"))
        {
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Decompress);
        }

        response.Headers.Remove("Content-encoding");
    }
}

我一直在谷歌搜索一段时间,但没有取得多大进展。据我所知,我应该使用“Request.GetResponseStream()”而不是响应对象,但我认为GetResponseStream需要非静态请求。

对任何事情开放。感谢。

DERP。就这样做:

CompressionManager.Decompress(HttpContext.Current.Error.Message);

public static void Decompress(string errorMsg)
{
    HttpContext.Current.Response.Filter = new DeflateStream(new MemoryStream(ASCIIEncoding.Default.GetBytes(errorMsg)), CompressionMode.Compress);
}

1 个答案:

答案 0 :(得分:1)

我建议您执行Response.Clear,然后设置相应的标头,然后发送数据。你不能以这种方式读取响应流是正确的。

可能是您的响应流是由IIS中的设置压缩的,您无法通过代码更改此设置。更新IIS压缩设置,然后重试。