Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support compressed HTTP requests in Asp.Net 4.0 / IIS7?

For an ASP.NET 4.0 / IIS7 web app, I would like to support compressed HTTP requests. Basically, I would like to support clients that would add Content-Encoding: gzip in the request headers, and compress the body accordingly.

Does anyone known how I achieve such a behavior?

Ps: concerning, I have multiple endpoints REST and SOAP, and it feels a better solution to support compression at the HTTP level rather than custom encoders for each endpoint.

like image 638
Joannes Vermorel Avatar asked Dec 10 '10 16:12

Joannes Vermorel


2 Answers

For those who might be interested, the implementation is rather straightforward with an IHttpModule that simply filters incoming requests.

public class GZipDecompressModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += BeginRequest;
    }

    void BeginRequest(object sender, EventArgs e)
    {
        var app = (HttpApplication)sender;

        if ("gzip" == app.Request.Headers["Content-Encoding"])
        {
            app.Request.Filter = new GZipStream(
               app.Request.Filter, CompressionMode.Decompress);
        }
    }

    public void Dispose()
    {
    }
}

Update: It appears that this approach trigger a problem in WCF, as WCF relies on the original Content-Length and not the value obtained after decompressing.

like image 92
Joannes Vermorel Avatar answered Oct 24 '22 18:10

Joannes Vermorel


Try Wiktor's answer to my similar question here:

How do I enable GZIP compression for POST (upload) requests to a SOAP WebService on IIS 7?

...but please note his implementation on his blog contained a couple of bugs / compatibility issues, so please try my patched version of the HttpCompressionModule class posted on the same page.

like image 36
NickG Avatar answered Oct 24 '22 19:10

NickG