2010-03-08 90 views
1

我寫了一個IHttpModule,它使用gzip(我返回大量數據)壓縮我的響應,以減少響應大小。 只要Web服務不引發異常,它就會很好地工作。 在引發異常的情況下,gzipped發生異常,但Content-encoding頭部消失,客戶端不知道讀取異常。json ihttpmodule壓縮

我該如何解決這個問題?爲什麼標題丟失?我需要在客戶端中獲得例外。

這裏是模塊:

public class JsonCompressionModule : IHttpModule 
{ 
    public JsonCompressionModule() 
    { 
    } 

    public void Dispose() 
    { 
    } 

    public void Init(HttpApplication app) 
    { 
     app.BeginRequest += new EventHandler(Compress); 
    } 

    private void Compress(object sender, EventArgs e) 
    { 
     HttpApplication app = (HttpApplication)sender; 
     HttpRequest request = app.Request; 
     HttpResponse response = app.Response; 
     try 
     { 
      //Ajax Web Service request is always starts with application/json 
      if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")) 
      { 
       //User may be using an older version of IE which does not support compression, so skip those 
       if (!((request.Browser.IsBrowser("IE")) && (request.Browser.MajorVersion <= 6))) 
       { 
        string acceptEncoding = request.Headers["Accept-Encoding"]; 

        if (!string.IsNullOrEmpty(acceptEncoding)) 
        { 
         acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture); 

         if (acceptEncoding.Contains("gzip")) 
         { 
          response.AddHeader("Content-encoding", "gzip"); 
          response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); 
         } 
         else if (acceptEncoding.Contains("deflate")) 
         { 
          response.AddHeader("Content-encoding", "deflate"); 
          response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); 
         } 
        } 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      int i = 4; 
     } 
    } 
} 

這裏是Web服務:

[WebMethod] 
public void DoSomething() 
{ 
    throw new Exception("This message get currupted on the client because the client doesn't know it gzipped."); 
} 

我任何並欣賞幫助。

謝謝!

+0

嘿,我真的需要幫助! – Naor 2010-03-14 22:15:28

回答

1

即使它已經有一段時間,因爲你張貼了這個問題,我只是有同樣的問題,這裏是我如何固定它:

在init()方法中,添加的處理程序錯誤事件

app.Error += new EventHandler(app_Error); 

在處理程序中,從Response頭中刪除Content-Type,並將Response.Filter屬性設置爲null。

void app_Error(object sender, EventArgs e) 
{ 

    HttpApplication httpApp = (HttpApplication)sender; 
    HttpContext ctx = HttpContext.Current; 

    string encodingValue = httpApp.Response.Headers["Content-Encoding"]; 

    if (encodingValue == "gzip" || encodingValue == "deflate") 
    { 
     httpApp.Response.Headers.Remove("Content-Encoding"); 
     httpApp.Response.Filter = null; 
    } 

} 

也許有一個更優雅的方式來做到這一點,但爲我做了詭計。

+1

這並沒有幫助我。此方法刪除了Content-Encoding標頭,但在我的情況下,數據被壓縮,但是此標頭丟失。 – Naor 2011-07-29 13:26:38