2012-06-20 66 views
0

我有一個啓用Gzip壓縮的REST API,它使用ASP.net WebAPI庫開發。當我使用的WebAPI測試工具,我可以看到下面的標題:使用基於ASP.Net的REST API進行Gzip壓縮

Date: Wed, 20 Jun 2012 14:50:14 GMT 
     Content-Encoding: gzip 
     X-AspNet-Version: 4.0.30319 
     X-Powered-By: ASP.NET 
     Content-Length: 1028 

在我的客戶端應用程序調用我的WS:

HttpWebRequest req = (HttpWebRequest)System.Net.WebRequest.Create(URI); 
      req.ContentType = "application/json"; 
      req.Method = "POST";     
      req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate"); 
      req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; 


      // Add parameters to post 
      byte[] data = System.Text.Encoding.Default.GetBytes(Parameters); 
      req.ContentLength = data.Length; 
      System.IO.Stream os = req.GetRequestStream(); 
      os.Write(data, 0, data.Length); 
      os.Close(); 

      try 
       { 
        string result = null; 
        using (HttpWebResponse resp1 = req.GetResponse() 
                as HttpWebResponse) 
        { 
         StreamReader reader = 
          new StreamReader(resp1.GetResponseStream()); 
         result = reader.ReadToEnd();       

         return result; 
        } 
       } 
      catch (WebException ex) 
      { 
       System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()); 
       string outputData = sr.ReadToEnd().Trim(); 

       throw new Exception(string.Format("Error {0} From WebService call", outputData)); 
      } 

我的問題是,resp1.ContentEncoding總是空的。如果我在IIS服務器上打開或關閉gzip壓縮,result.length總是相同的。我究竟做錯了什麼?

+0

當我在IIS中關閉壓縮時,StreamReader.BaseStream類型是System.Web.ConnectStream,它在它上面時是System.Web.GZipWrapperStream類型。 – keitn

回答

1

使用System.Net.WebClient而不是System.Net.WebRequest解決了這個問題。