向自托管 WCF 服务添加可选的 gzip 压缩

rek*_*ire 3 rest wcf gzip custom-attributes

如何为我的自托管 WCF 服务添加可选的 gzip 压缩?我在这个场景中使用WebHttpBinding. 我想检查Accept标头是否包含字符串gzip并压缩内容。

我想使用自定义属性。到目前为止,我目前使用自定义属性允许我在 XML 和 JSON 输出之间切换,但我现在不知道如何压缩输出。

在我的编码器开关属性中,我实现了IDispatchMessageFormatter按需更改XmlObjectSerializer. 但我不明白如何生成输出来修改它。

如果有人能给我指出一个可能的解决方案,那就太好了。

Sco*_*ord 5

这不是属性,但它是压缩 WCF 服务响应的基本代码,如果需要,可以将其包装到属性中。

public static void CompressResponseStream(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"))
        {
            context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
            context.Response.AppendHeader("Content-Encoding", "deflate");
            context.Response.AppendHeader("X-CompressResponseStream", "deflate");
        }
        else if (encodings.Contains("gzip"))
        {
            context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
            context.Response.AppendHeader("Content-Encoding", "gzip");
            context.Response.AppendHeader("X-CompressResponseStream", "gzip");
        }
        else
        {
            context.Response.AppendHeader("X-CompressResponseStream", "no-known-accept");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

[编辑]解决评论:

只需在 Web 服务操作主体中的任意位置调用它即可,因为它会设置响应的属性:

[OperationContract]
public ReturnType GetInformation(...) {
    // do some stuff
    CompressResponseStream();
}
Run Code Online (Sandbox Code Playgroud)