c# - OData中解压gzip

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

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

这是我的代码:

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);      
    }

现在我收到一个错误:

Unable to translate bytes [8B] at index 1 from the specified code page to Unicode.

在这部分代码中:

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

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

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

最佳答案

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

我使用了sendingRequest2:

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

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

关于c# - OData中解压gzip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25864503/

相关文章:

c# - IDictionary 到字符串

c# - 如何在 C# 中转换为 XML 之前验证 JSON 字符串

c# - 具有多个绑定(bind)的 ServiceHostFactory

c# - 如何在 WCF 中将 Noda Time(或任何第三方类型)对象作为参数传递?

javascript - 带有 webpack 的 Vue.js 不提供压缩的 GZIP .js 文件

linux - 如何gzip文件并保留原始扩展名?

google-app-engine - Google App Engine 中的 GZIP 内容使用 django-nonrel

c# - 使用枚举更新对象的字符串属性

c# - 如何在 C# 中查找对象类型?

vb.net - 如何获取WCF请求的base64签名编码