启用gzip/deflate压缩

6

我正在使用 ServiceStack(版本3.9.44.0)作为Windows服务(因此我没有使用IIS),并且同时使用其作为API和用于提供网页的功能。

然而,我一直没有找到如何在客户端支持时启用压缩的确切方法。

我想象ServiceStack会在客户端请求包含Accept-Encoding: gzip,deflate标头时以透明方式压缩数据,但是我没有看到任何相应的Content-Encoding:gzip在返回的响应中。

所以我有几个相关的问题:

  1. 在不使用IIS的情况下使用ServiceStack作为独立服务时,如何在浏览器接受它时启用响应的压缩。

  2. 在C#客户端的情况下,类似地如何确保客户端/服务器之间的通信被压缩。

如果我遗漏了什么,请提供建议,谢谢!

2个回答

9
如果您想在整个API范围内启用压缩,另一个选项是执行以下操作:
将此覆盖添加到您的AppHost中:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
    return new MyServiceRunner<TRequest>(this, actionContext);
}

那么就像这样实现那个类:
public class MyServiceRunner<TRequest> : ServiceRunner<TRequest>
{
    public MyServiceRunner(IAppHost appHost, ActionContext actionContext) : base(appHost, actionContext)
    {
    }

    public override void OnBeforeExecute(IRequestContext requestContext, TRequest request)
    {
        base.OnBeforeExecute(requestContext, request);
    }

    public override object OnAfterExecute(IRequestContext requestContext, object response)
    {
        if ((response != null) && !(response is CompressedResult))
            response = requestContext.ToOptimizedResult(response);

        return base.OnAfterExecute(requestContext, response);
    }

    public override object HandleException(IRequestContext requestContext, TRequest request, Exception ex)
    {
        return base.HandleException(requestContext, request, ex);
    }
}

在执行完成后,将调用OnAfterExecute并给你修改响应的机会。在这里,我对除了空值和已经压缩过的内容进行了压缩(以防我在其他地方使用ToOptimizedResultUsingCache)。如果需要,您可以更加有选择性,但在我的情况下,我所有的POCO对象都是json格式。

参考资料


7

对于那些感兴趣的人,我自己的问题有一个部分答案,你可以使用扩展方法ToOptimizedResult(),或者如果你正在使用缓存,则可以使用ToOptimizedResultUsingCache()

例如,返回一个压缩结果:

public class ArticleService : Service
{
  public object Get(Articles request) {
    return base.RequestContext.ToOptimizedResult( 
       new List<Articles> { 
            new Article {Ref = "SILVER01", Description = "Silver watch"},
            new Article {Ref = "GOLD1547", Description = "Gold Bracelet"}
       });
  }
}

参考资料

注意:请勿删除HTML标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接