2009-11-13 26 views
4

您好,我需要從ASHX提供一個GZ壓縮文件。在代碼中,我已經有了明確的字符串:生成並提供在ASP.NET中壓縮的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(); 
} 

現在,我需要在GZ

任何幫助?

+0

我們不是按需生成的文件,而是一個時間表。由於我們的站點地圖包含近一百萬個URL,因此這些數據會變得非常多。我們在生成文件時壓縮內容,然後將文件存儲在cdn中,以便在請求時由前端提供服務。 – 2010-05-13 15:51:03

回答

4

,你可以在enable compression IIS級別爲特定的目錄。我相信這會比在通用處理程序中手動更有效。


UPDATE:

你可以使用GZipStream將XML直接壓縮到thew響應流:

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

客戶端需要收到一個gz壓縮文件。我不想gzip HTTP消息 – Robert 2009-11-13 21:40:01

+0

謝謝!似乎工作! – Robert 2009-11-13 22:28:12

+0

這不是此應用程序的正確標題,這就是您收到gzip文件的原因。 Content-Type應該仍然是text/xml或application/xml Content-Encoding標頭應該被添加並設置爲gzip。 – AaronM 2017-12-06 18:13:18