I am trying to compress the output stream for my WCF service but for some reason when i compress and return the compressed stream i get empty response, although when i check on disk i see the compressed file does exist.
the method that does the compression:
public static Stream CompressResponseStream(FileStream stream,string filename, HttpContext context = null)
{
if (context == null)
context = HttpContext.Current;
string encodings = context.Request.Headers.Get("Accept-Encoding");
if (!string.IsNullOrEmpty(encodings))
{
encodings = encodings.ToLowerInvariant();
if (encodings.Contains("deflate"))
{
using (FileStream fs = File.OpenWrite($"{filename}.gzip"))
using (var deflateStream = new DeflateStream(fs, CompressionMode.Compress))
{
stream.CopyTo(deflateStream);
context.Response.AppendHeader("Content-Encoding", "deflate");
context.Response.AppendHeader("X-CompressResponseStream", "deflate");
fs.Flush();
return fs;
}
}
else if (encodings.Contains("gzip"))
{
FileStream fs = new FileStream($"{filename}.gzip", FileMode.Create, FileAccess.ReadWrite);
using (var gZipStream = new GZipStream(fs, CompressionMode.Compress))
{
stream.CopyTo(gZipStream);
context.Response.AppendHeader("Content-Encoding", "gzip");
context.Response.AppendHeader("X-CompressResponseStream", "gzip");
fs.Flush();
return fs;
}
}
else
{
context.Response.AppendHeader("X-CompressResponseStream", "no-known-accept");
}
}
return stream;
}