I changed the output type of my methods: they all return a Stream now.
So at the end of each method, instead of doing:
return myObject;
I now do :
return GetStream(myObject); private Stream GetStream(object o) { MemoryStream ms1 = new MemoryStream(); MemoryStream ms2; DataContractJsonSerializer dcjs = new DataContractJsonSerializer(o.GetType()); dcjs.WriteObject(ms1, o); string AcceptEncoding = WebOperationContext.Current.IncomingRequest.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))) { byte[] raw = ms1.ToArray(); ms1.Close(); ms2 = new MemoryStream(); if (AcceptEncoding.Contains("gzip")) { Logger.MainLogger.Info("gzip actif", AcceptEncoding, "GZipEncodePage"); HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip"); GZipStream compress = new GZipStream(ms2, CompressionMode.Compress); compress.Write(raw, 0, raw.Length); compress.Close(); } else { Logger.MainLogger.Info("deflate actif", AcceptEncoding, "GZipEncodePage"); HttpContext.Current.Response.AppendHeader("Content-Encoding", "deflate"); DeflateStream compress = new DeflateStream(ms2, CompressionMode.Compress); compress.Write(raw, 0, raw.Length); compress.Close(); } } else { ms2 = ms1; } return new MemoryStream(ms2.ToArray()); }
and all works well... :)
The only side effect so far is that my http response now has Content-Type = "application/octet-stream" (instead of "application/json")
Hello
I'm trying to compress the output of a WCF restful service, using GZipStream:
I put this in my global.asax:
The problem is that the field "Content-Length" of the response header still gets the value of the uncompressed stream.
For example, when I use fiddler to see what happens:
response header:
HTTP/1.1 200 OK
Date: Thu, 16 Feb 2012 14:25:32 GMT
Cache-Control: private
Content-Length: 472810
Content-Type: application/json
Content-Encoding: gzip
Vary: Content-Encoding
But I also get a fiddler pop up with the error:
Fiddler has detected a protocol violation in session #569.
Content-Length mismatch: Response Header indicated 472 810 bytes, but server sent 152 488 bytes.
Do you know what I've done wrong ?
Thanks