使用JsonSerializer和DeflateStream在WCF中返回压缩流

时间:2017-03-30 09:50:13

标签: c# .net wcf stream json.net

现在我正在使用JSON.net JsonSerializer从我的WCF服务中作为流返回数据。代码是这样的:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public Stream GetJSON()
{
    Dictionary<string, string> resultDict = new Dictionary<string, string>();
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return SerializeToJSON(resultDict);
}

public static Stream SerializeToJSON(object value)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    JsonTextWriter jsonWriter = new JsonTextWriter(writer);
    JsonSerializer ser = new JsonSerializer();

    ser.Formatting = Formatting.None;
    ser.Serialize(jsonWriter, value);
    jsonWriter.Flush();
    stream.Position = 0;
    return stream;
}

我想知道是否可以在某处添加DeflateStream并返回压缩数据。

直接将其添加到SerializeToJSON方法是行不通的,因为在将数据返回给客户端之前,我无法处理流或WCF关闭它们。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案并重新编写了代码以更好地处理流。 根据我的理解,无法处理返回的流,因为WCF需要它们来处理返回的数据

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public Stream GetJSON()
{
    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    WebOperationContext.Current.OutgoingResponse.Headers["Content-Encoding"] = "gzip";
    Dictionary<string, string> resultDict = new Dictionary<string, string>();
    return Compress(SerializeToJSON(resultDict));
}

public static Stream SerializeToJSON(object value)
{
    var resultStream = new MemoryStream();
    using (var jsonStream = new MemoryStream())
    using (var writer = new StreamWriter(jsonStream))
    using (var jsonWriter = new JsonTextWriter(writer))
    {
        var jsonSer = new JsonSerializer();
        jsonSer.Formatting = Formatting.None;
        jsonSer.Serialize(jsonWriter, value);
        jsonWriter.Flush();
        resultStream = new MemoryStream(jsonStream.ToArray());
    }
    return resultStream;
}

public static Stream Compress(Stream plainStream)
{
    var resultStream = new MemoryStream();
    using (var compressedStream = new MemoryStream())
    using (var compressor = new GZipStream(compressedStream, CompressionMode.Compress))
    {
        plainStream.CopyTo(compressor);
        compressor.Close();
        resultStream = new MemoryStream(compressedStream.ToArray());
    }
    return resultStream;
}