WCF 在压缩时返回空蒸汽

本文关键字:返回 压缩 WCF | 更新日期: 2023-09-27 18:36:10

我正在尝试压缩WCF服务的输出流,但由于某种原因,当我压缩并返回压缩流时,我得到空响应,尽管当我检查磁盘时,我看到压缩文件确实存在。

执行压缩的方法:

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

WCF 在压缩时返回空蒸汽

问题是它实际上没有写入磁盘,直到我关闭流,所以我不得不关闭流,然后重新打开压缩文件的文件流