views:

30

answers:

1

Hello All,

Is anybody know, is it possible to compress my outgoing http data in IE? I perform ajax requests to a server and want to reduce amount of traffic in order to speed up my app.

Thanks, Egor

+2  A: 

The following is a common way to create a compression filter attribute:

public class CompressFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext actionContext)
    {
        HttpRequestBase request = actionContext.HttpContext.Request;

        string acceptEncoding = request.Headers["Accept-Encoding"];

        if (!string.IsNullOrWhiteSpace(acceptEncoding))
        {
            acceptEncoding = acceptEncoding.ToLowerInvariant();
            HttpResponseBase response = actionContext.HttpContext.Response;

            if (acceptEncoding.Contains("gzip"))
            {
                response.AddHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                response.AddHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }
}

Now you can decorate your controller with a [CompressFilter] attribute. It will add a compression header to the response for browsers that support it, which IIS will pick up. If you have switched on Dynamic Compression, IIS will then output compressed responses.

Jappie
That code allows to compress server response. But I want to compress request.
Egor4eg
AFAIK, no browser is capable of implicitly compressing request calls. I suppose what you could do is find a javascript compression library and post the client-compressed data to the server and manually decompress it there. Probably the overhead that this would cost on the client is more than the time you save uploading the data.
Jappie
yes, probably it would cost more time. But I have to check it. Do you know any javascript libraries which allow to do that?
Egor4eg
You can look at [this post](http://stackoverflow.com/questions/294297/javascript-implementation-of-gzip). However keep in mind that the result will have to be serialized (in base64 for example) which will again lose a big chunk of the compression.
Jappie
Thanks a lot. I'm going to do these tests in several days. I'll let you know the results.
Egor4eg
You can also try [this one](http://code.google.com/p/jslzjb/).
Jappie