What is the easiest way to add compression to WCF in Silverlight?

后端 未结 4 1418
孤独总比滥情好
孤独总比滥情好 2020-12-23 17:52

I have a silverlight 2 beta 2 application that accesses a WCF web service. Because of this, it currently can only use basicHttp binding. The webservice will return fairly

4条回答
  •  既然无缘
    2020-12-23 17:57

    I didn't see a native way for WCF to do compression when doing a WCF project recently. I just used the System.IO.Compression namespace and made a quick compressor. Here's the code i used

    public static class CompressedSerializer
    {
        /// 
        /// Decompresses the specified compressed data.
        /// 
        /// 
        /// The compressed data.
        /// 
        public static T Decompress(byte[] compressedData) where T : class
        {
            T result = null;
            using (MemoryStream memory = new MemoryStream())
            {
                memory.Write(compressedData, 0, compressedData.Length);
                memory.Position = 0L;
    
                using (GZipStream zip= new GZipStream(memory, CompressionMode.Decompress, true))
                {
                    zip.Flush();
                    var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    result = formatter.Deserialize(zip) as T;
                }
            }
    
            return result;
        }
    
        /// 
        /// Compresses the specified data.
        /// 
        /// 
        /// The data.
        /// 
        public static byte[] Compress(T data)
        {
            byte[] result = null;
            using (MemoryStream memory = new MemoryStream())
            {
                using (GZipStream zip= new GZipStream(memory, CompressionMode.Compress, true))
                {
                    var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    formatter.Serialize(zip, data);
                }
    
                result = memory.ToArray();
            }
    
            return result;
        }
    }
    

    then i just had my services take in a byte array as an input, like such

    void ReceiveData(byte[] data);
    

    Worked out well for me.

提交回复
热议问题