开发者

Generate and serving gz compressed in ASP.NET

Hi I need to serve from a ASHX a GZ compressed file. In the code I already have the string in clear:

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

    Response.ContentEncoding = E开发者_如何学编程ncoding.UTF8;
    Response.ContentType = "text/xml";

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

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

Now and I need to

  • compress xml in GZ (for a compressed sitemap file http://www.sitemaps.org/protocol.php#sitemapXMLExample)
  • send it to the Response.OutputStream
  • set some HTTP response header (content type, encoding, ecc.)

Any help?


You could enable compression at IIS level for a specific directory. I believe this will be more efficient than doing it by hand in the generic handler.


UPDATE:

You could use GZipStream to compress the xml directly to thew response stream:

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);
    }
}


GZip compression is supported in ASP.NET. A quick Google resulted in these posts which seem to help:

http://west-wind.com/WebLog/posts/10294.aspx - doing GZip
http://www.west-wind.com/Weblog/posts/10564.aspx - returning the result

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜