如何在WCF服务中处理压缩请求

时间:2015-02-02 07:00:53

标签: wcf

我们在IIS 7上使用.NET Framework 4.5托管了WCF REST服务。客户端使用请求标头以GZip压缩格式发送数据:

内容编码:gzip Content-Type:application / xml

但是如果请求是压缩格式的话,我们收到来自服务器的错误请求。我们通过实现IHttpModule来启用请求压缩,IHttpModule将过滤/修改传入的请求。根据我的理解,这是失败的,因为WCF使用原始内容长度(压缩数据的长度)而不是解压缩数据。所以这是我的问题:

我们有什么办法可以解决IIS7 / .NET 4.5中的内容长度问题吗?我的HTTP模块实现如下:

httpApplication.Request.Filter = New GZipStream(httpApplication.Request.Filter,CompressionMode.Decompress)`

如果在服务器端无法解决内容长度问题,我是否可以通过压缩请求从客户端发送原始内容长度?客户端实现如下:

using (Stream requeststream = serviceRequest.GetRequestStream())
{
   if (useCompression)
   {
       using (GZipStream zipStream = new GZipStream(requeststream, CompressionMode.Compress))
       {
           zipStream.Write(bytes, 0, bytes.Length);
           zipStream.Close();
           requeststream.Close();
       }

       serviceRequest.Headers.Add("Content-Encoding", "gzip");
   }
   else
   {
       requeststream.Write(bytes, 0, bytes.Length);
       requeststream.Close();
   }
}

1 个答案:

答案 0 :(得分:-1)

我能够使用wsHTTPBinding使gzip在WCF中工作,并将其作为Web请求的基础:

private HttpWebRequest GetWebRequest()
{
  dynamic objHTTPReq = (HttpWebRequest)WebRequest.CreateDefault(_URI);
  objHTTPReq.ContentType = "text/xml; charset=\"utf-8\"";
  objHTTPReq.Method = "POST";
  objHTTPReq.Accept = "gzip, deflate";
  objHTTPReq.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; OfficeLiveConnector.1.3;OfficeLivePatch.0.0; Zune 3.0; MS-RTC LM 8)";
  objHTTPReq.Headers.Add("SOAPAction", "http://xxx.yyyy.zzzz");
  return objHTTPReq;
}

所以试一试。祝你好运。