0

我有一个启用了 Gzip 压缩的 REST api,它是使用 ASP.net WebAPI 库开发的。当我使用 WebAPI 测试工具时,我可以看到以下标题:

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 总是相同的。我究竟做错了什么?

4

1 回答 1

1

使用 System.Net.WebClient 而不是 System.Net.WebRequest 解决了这个问题。

于 2012-06-25T08:27:36.900 回答