OData中的解压缩gzip

时间:2014-09-16 08:55:35

标签: c# wcf gzip wcf-data-services compression

我需要帮助解压缩 gzip WCF DataService响应,因为我配置了 IIS 来压缩响应。我正在发送请求标头Accept-Encoding gzip,收缩,但现在我找不到任何帮助我如何从数据库中获取所选实体(例如客户端)。

这是我的代码:

DbServiceReference.MainDBEntities proxy;
string message;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        proxy = new MainDBEntities(new Uri("http://localhost/DotConnectTest/MainDbDataServices.svc/"));


        proxy.BuildingRequest += proxy_BuildingRequest;
        proxy.ReceivingResponse += proxy_ReceivingResponse;


        txtBox.Text = proxy.Clients.FirstOrDefault().Name;
    }


    void proxy_ReceivingResponse(object sender, System.Data.Services.Client.ReceivingResponseEventArgs e)
    {   
        Stream stream = new GZipStream(e.ResponseMessage.GetStream(), CompressionMode.Decompress);
        message = Encoding.UTF8.GetString(ReadFully(stream)); // here I can Encode Response to string contains Client object in xml                         
    }

    public static byte[] ReadFully(Stream input)
    {
        byte[] buffer = new byte[16 * 1024];
        using (MemoryStream ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }

    void proxy_BuildingRequest(object sender, System.Data.Services.Client.BuildingRequestEventArgs e)
    {
        KeyValuePair<string, string> header = new KeyValuePair<string,string>("Accept-Encoding", "gzip, deflate");
        if (!e.Headers.Contains(header))
            e.Headers.Add(header);      
    }

现在我收到一个错误:

  

无法将索引1处的字节[8B]从指定的代码页转换为Unicode。

在这部分代码中:

txtBox.Text = proxy.Clients.FirstOrDefault().Name;

我找到了教程,其中我看到了如何使用 ReadingResponse 事件,但我认为新版本的数据服务ReadingResponse 事件不存在。我只有ReceivingResponse事件,但在那里我无法覆盖收到的消息的内容。

有任何想法如何解决这个问题?如何获取客户端名称并将其设置为textBox.Text属性?

1 个答案:

答案 0 :(得分:2)

好的,我知道如何最终解决我的问题!

我使用 sendingRequest2

void proxy_SendingRequest2(object sender, System.Data.Services.Client.SendingRequest2EventArgs e)
    {
        var Request = ((HttpWebRequestMessage)e.RequestMessage).HttpWebRequest;

        Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    }