Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

servicestack - Enable gzip/deflate compression

I'm using ServiceStack (version 3.9.44.0) as a Windows Service (so I'm not using IIS) and I use both its abilities both as an API and for serving web pages.

However, I haven't been able to find how exactly I should enable compression when the client supports it.

I imagined that ServiceStack would transparently compress data if the client's request included the Accept-Encoding:gzip,deflate header, but I'm not seeing any corresponding Content-Encoding:gzip in the returned responses.

So I have a couple of related questions:

  1. In the context of using ServiceStack as a standalone service (without IIS), how do I enable compression for the responses when the browser accepts it.

  2. In the context of a C# client, how do similarly I ensure that communication between the client/server is compressed.

If I'm missing something, any help would be welcome.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to enable compression globally across your API, another option is to do this:

Add this override to your AppHost:

public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
    return new MyServiceRunner<TRequest>(this, actionContext);
}

Then implement that class like this:

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 will be called and give you the chance to change the response. Here, I am compressing anything that is not null and not already compressed (in case I'm using ToOptimizedResultUsingCache somewhere). You can be more selective if you need to but in my case, I'm all POCO objects with json.

References


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...