【问题标题】:Generate and serving gz compressed in ASP.NET生成并提供在 ASP.NET 中压缩的 gz
【发布时间】:2009-11-13 16:07:56
【问题描述】:

您好,我需要从 ASHX 提供 GZ 压缩文件。在代码中,我已经清楚地知道了字符串:

public void ProcessRequest(HttpContext context)
{
    // this is the code without compression
    HttpRequest Request = context.Request;
    HttpResponse Response = context.Response;

    Response.ContentEncoding = Encoding.UTF8;
    Response.ContentType = "text/xml";

    // this is the string to compress and send to the client
    string xml = GenerateXml();

    Response.Write(output);
    Response.End();
}

现在我需要

有什么帮助吗?

【问题讨论】:

  • 我们不是按需生成文件,而是按计划生成文件。因为我们的站点地图包含近一百万个 URL,所以这些数据非常多。我们在生成文件时压缩内容,然后将文件存储在 cdn 上,以便在前端请求时提供服务。

标签: c# asp.net gzip


【解决方案1】:

您可以在 IIS 级别为特定目录enable compression。我相信这会比在通用处理程序中手动执行更有效。


更新:

您可以使用GZipStream 将 xml 直接压缩为 w 响应流:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "application/x-gzip";
    var xml = "<xml/>";
    using (var gzipStream = new GZipStream(context.Response.OutputStream, CompressionMode.Compress))
    {
        var buffer = Encoding.UTF8.GetBytes(xml);
        gzipStream.Write(buffer, 0, buffer.Length);
    }
}

【讨论】:

  • 客户端需要收到一个gz压缩文件。我不想压缩 HTTP 消息
  • 这不是此应用程序的正确标头,这就是您收到 gzip 压缩文件的原因。 Content-Type 仍应为 text/xml 或 application/xml 应添加 Content-Encoding 标头并将其设置为 gzip。
【解决方案2】:

ASP.NET 支持 GZip 压缩。快速谷歌搜索到这些似乎有帮助的帖子:

http://west-wind.com/WebLog/posts/10294.aspx - 执行 GZip
http://www.west-wind.com/Weblog/posts/10564.aspx - 返回结果

【讨论】:

  • 接近解决方案,谢谢。我需要提供一个应用程序/x-gzip 文件 - 不确定如何继续