0
我遇到了一個問題,當我的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");
}
}
我一直在Google上搜索一段時間,但沒有取得太大的進展。據我所知,我應該使用「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);
}
你給了我一個很棒的主意,其中超級簡單。讓我編輯我的帖子。 –