Enable gzip / deflate compression

I use ServiceStack (version 3.9.44.0) as a Windows service (so I do not use IIS) and I use both of its features both API and for serving web pages.

However, I could not find a way to enable compression when the client supports it.

I assumed that ServiceStack would transparently compress data if the client request included the Accept-Encoding:gzip,deflate header, but I do not see the corresponding Content-Encoding:gzip in the returned responses.

So, I have a few related questions:

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

  • In the context of a C # client, how I similarly guarantee that the connection between the client / server is being compressed.

If I am missing something, any help would be appreciated.

Thanks.

+6
source share
2 answers

If you want to enable compression globally for your API, you need to do the following:

Add this override to AppHost:

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

Then we implement this class as follows:

 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 will give you the opportunity to change the answer. Here I am compressing everything that is not null and not compressed (in case I use ToOptimizedResultUsingCache somewhere). You may be more selective if you need to, but in my case, I am all POCO objects with json.

References

+9
source

For those interested, a partial answer to my own question, you can use the ToOptimizedResult() extension method or, if you use ToOptimizedResultUsingCache() caching.

For example, returning a compressed result:

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

References

+7
source

Source: https://habr.com/ru/post/944718/


All Articles