有人使用ASP.NET进行HTTP压缩吗?

时间:2010-12-21 06:14:55

标签: asp.net http compression gzip

我花了很多时间在这上面,但似乎无处可去。我有一个很大的页面,我真的想加快。显而易见的起点似乎是HTTP压缩,但我似乎无法让它为我工作。

经过大量搜索,我尝试了以下代码的几种变体。它有点工作,但刷新浏览器后,结果似乎崩溃了。当页面使用缓存时,他们转向垃圾。如果我关闭缓存,那么页面似乎正确,但我丢失了我的CSS格式(存储在一个单独的文件中)并得到一个错误,包含的JS文件包含无效字符。

我在网上找到的大部分资源要么非常陈旧,要么专注于直接访问IIS。我的页面在共享主机帐户上运行,我无法直接访问正在运行的IIS7。

protected void Application_BeginRequest(object sender, EventArgs e)
{
    // Implement HTTP compression
    if (Request["HTTP_X_MICROSOFTAJAX"] == null) // Avoid compressing AJAX calls
    {
        // Retrieve accepted encodings
        string encodings = Request.Headers.Get("Accept-Encoding");
        if (encodings != null)
        {
            // Verify support for or gzip (deflate takes preference)
            encodings = encodings.ToLower();
            if (encodings.Contains("gzip") || encodings == "*")
            {
                Response.Filter = new GZipStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "gzip");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
            else if (encodings.Contains("deflate"))
            {
                Response.Filter = new DeflateStream(Response.Filter,
                    CompressionMode.Compress);
                Response.AppendHeader("Content-Encoding", "deflate");
                Response.Cache.VaryByHeaders["Accept-encoding"] = true;
            }
        }
    }
}

有人在这方面取得了更大的成功吗?

1 个答案:

答案 0 :(得分:1)

虽然我不熟悉GZipStream属性,但使用DeflateStreamResponse.Filter直接编写输出我得到了很好的结果。给这个旋转:

string response = "your output body";
string accept = Request.Headers["Accept-Encoding"];
if(accept == null) accept = "";
if (response.Length < 100 || !(accept.Contains("deflate") || accept.Contains("gzip")))
    Response.Write(response);
else
{
    byte[] compressed;
    bool useDeflate = accept.Contains("deflate");
    using (MemoryStream stream = new MemoryStream())
    {
        using (Stream deflate = useDeflate
            ? (Stream)new DeflateStream(stream, CompressionMode.Compress, true)
            : (Stream)new GZipStream(stream, CompressionMode.Compress, true))
        using (StreamWriter writer = new StreamWriter(deflate))
            writer.Write(response);
        compressed = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(compressed, 0, compressed.Length);
    }
    Response.Headers["Content-Encoding"] = useDeflate ? "deflate" : "gzip";
    Response.BinaryWrite(compressed);
}