Click here to Skip to main content
12,954,276 members (89,454 online)
Click here to Skip to main content
Add your own
alternative version


62 bookmarked
Posted 6 Jan 2006

HTTP compression in the .NET Framework 1.1

, 6 Jan 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on HTTP compression in the .NET Framework 1.1.


This article will show how to request for HTTP compression and handle a compressed response from a web server (or any appliance connected to the server) without changing the client application.

The factory pattern of creating WebRequest instances

The WebRequest supplies two methods to create instances:

The WebRequest class uses instances of classes that implement the IWebRequestCreate interface and are registered in the webRequestModules section in the configuration files. The Create method (called by both CreateDefault and Create) returns an initialized instance of a WebRequest descendent class capable of performing a standard request/response transaction for the protocol without needing any protocol-specific fields modified.

Because we can control the WebRequest factory using the configuration files, we can change the behavior of already built applications (our applications, or even the .NET Framework) to request and handle HTTP compression without changing them.

The WebRequest descendent instances will be responsible to create the WebResponse descendent instance that will handle the response from the web server.

The code

As shown before, to add HTTP compression to our applications, we just have to build three classes:

  • CompressibleHttpRequestCreator - implementing the IWebRequestCreate interface.
  • CompressibleHttpWebRequest - derived from WebRequest.
  • CompressibleHttpWebResponse - derived from WebResponse.

    In order for the applications that use HttpWebRequest and HttpWebResponse to work without any changes, CompressibleHttpWebRequest has to derive from HttpWebRequest, and CompressibleHttpWebResponse has to derive from HttpWebResponse.

    Fortunately, HttpWebRequest and HttpWebResponse are not sealed (NotInheritable in VB.NET). Unfortunately, these classes don't have any public constructor, and the only protected constructor each one has is the one required by the implementation of the ISerializable interface. Due to this drawback, reflection must be used.


    This is the class that will be implementing the IWebRequestCreate interface and is used to create HttpWebRequest descendant instances.

    As mentioned before, the only way to create an instance of a HttpWebRequest derived class, is by deserialization. To accomplish this, an instance of HttpWebRequest will be created, serialized, and deserialized into an instance of CompressibleHttpWebRequest.

    public class CompressibleHttpRequestCreator : IWebRequestCreate
        WebRequest IWebRequestCreate.Create(Uri uri)
            ISerializable httpWebRequest = Activator.CreateInstance(
                BindingFlags.CreateInstance | BindingFlags.Public | 
                BindingFlags.NonPublic | BindingFlags.Instance,
                new object[] { uri },
                null) as ISerializable;
            if (httpWebRequest == null)
                return null;
            SerializationInfo serializationInfo = new SerializationInfo(
                typeof(CompressibleHttpWebRequest), new FormatterConverter());
            StreamingContext streamingContext = 
                new StreamingContext(StreamingContextStates.All);
            httpWebRequest.GetObjectData(serializationInfo, streamingContext);
            CompressibleHttpWebRequest webRequest = new 
                CompressibleHttpWebRequest(serializationInfo, streamingContext);
            webRequest.Method = serializationInfo.GetString("_OriginVerb");
            return webRequest;


    This class will handle the setup of the HTTP request and the creation of the HttpWebResponse derived instance to handle the response.

    As with CompressibleHttpWebRequest, when creating the HttpWebResponse, an instance of HttpWebResponse will be created, serialized, and deserialized into an instance of CompressibleHttpWebResponse.

    To specify what types of compression will be accepted in the response, the AcceptEncodings will be used. Its value will, also, be used to set the accept-encoding HTTP header in the request (in the BeginGetResponse). The possible values for AcceptEncodings are:

    • Identity - The default (identity) encoding; the use of no transformation whatsoever.
    • GZip - An encoding format produced by the file compression program "gzip" (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC.
    • Deflate - The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression mechanism described in RFC 1951 [29].
    public class CompressibleHttpWebRequest : HttpWebRequest
        private static FieldInfo m_UsesProxySemanticsFieldInfo = 
            BindingFlags.NonPublic | BindingFlags.Instance);
        private static FieldInfo m_ConnectStreamFieldInfo = 
            BindingFlags.NonPublic | BindingFlags.Instance);
        private AcceptEncodings acceptEncodings = AcceptEncodings.GZip | 
            AcceptEncodings.Deflate | AcceptEncodings.Identity;
        public AcceptEncodings AcceptEncodings
                return this.acceptEncodings;
                this.acceptEncodings = value;
        protected internal CompressibleHttpWebRequest(SerializationInfo 
                  serializationInfo, StreamingContext 
                  streamingContext) : base(serializationInfo, 
        public override IAsyncResult 
            BeginGetResponse(AsyncCallback callback, object state)
            if (this.acceptEncodings != AcceptEncodings.Identity)
                    (this.acceptEncodings & 
            return base.BeginGetResponse(callback, state);
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
            ISerializable httpWebResponse = 
               base.EndGetResponse(asyncResult) as ISerializable;
            if (httpWebResponse == null)
                return null;
            SerializationInfo serializationInfo = new 
                new FormatterConverter());
            StreamingContext streamingContext = new 
            httpWebResponse.GetObjectData(serializationInfo, streamingContext);
            CompressibleHttpWebResponse webResponse = new 
            return webResponse;


    This is the easiest one. All that's needed is to handle the response stream accordingly to the content-encoding HTTP response header. Unfortunately, the .NET Framework 1.1 base classes don't provide any class for handling Deflate and GZip streams. For that, the SharpZipLib will be used.

    public class CompressibleHttpWebResponse : HttpWebResponse
        public CompressibleHttpWebResponse(SerializationInfo 
            serializationInfo, StreamingContext streamingContext)
            : base(serializationInfo, streamingContext)
        public override Stream GetResponseStream()
            Stream stream = base.GetResponseStream();
            if (stream == null)
                return Stream.Null;
            if (string.Compare(ContentEncoding, "gzip", true) == 0)
                return new GZipInputStream(stream);
            else if (string.Compare(ContentEncoding, "deflate", true) == 0)
                return new InflaterInputStream(stream);
                return stream;


    Now, to add HTTP compression support to any application, all that's needed is to add the corresponding entry to the webRequestModules section in the configuration file.

    <?xml version="1.0" encoding="utf-8" ?>
                  <add prefix="http" 
                    type="PaJoCoMo.Net.CompressibleHttpRequestCreator, PaJoCoMo" />
  • License

    This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


    About the Author

    Paulo Morgado
    Software Developer (Senior) Paulo Morgado
    Portugal Portugal

    You may also be interested in...

    Comments and Discussions

    GeneralIt doesn't work in No touch deploy Pin
    nory29-Mar-07 16:24
    membernory29-Mar-07 16:24 
    GeneralRe: It doesn't work in No touch deploy Pin
    Paulo Morgado29-Mar-07 22:32
    memberPaulo Morgado29-Mar-07 22:32 
    GeneralRe: It doesn't work in No touch deploy Pin
    nory30-Mar-07 0:18
    membernory30-Mar-07 0:18 
    GeneralRe: It doesn't work in No touch deploy Pin
    Paulo Morgado1-Apr-07 8:24
    memberPaulo Morgado1-Apr-07 8:24 
    GeneralRe: It doesn't work in No touch deploy Pin
    nory1-Apr-07 16:12
    membernory1-Apr-07 16:12 
    GeneralNot attaching headers Pin
    kryzchek13-Sep-06 11:35
    memberkryzchek13-Sep-06 11:35 
    GeneralRe: Not attaching headers Pin
    Paulo Morgado13-Sep-06 11:41
    memberPaulo Morgado13-Sep-06 11:41 
    GeneralRe: Not attaching headers Pin
    kryzchek13-Sep-06 11:48
    memberkryzchek13-Sep-06 11:48 
    There is an "Accept-Encoding" header entry, and the value is "gzip, deflate".

    However, Fiddler reports my header for the request as:

    POST /LDI.Data/DataAccess.asmx HTTP/1.1
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 1.1.4322.2032)
    Content-Type: text/xml; charset=utf-8
    SOAPAction: ""
    Content-Length: 439
    Expect: 100-continue
    Proxy-Connection: Keep-Alive

    As you can see, no "Accept-Encoding" header entry.
    GeneralRe: Not attaching headers Pin
    Paulo Morgado13-Sep-06 13:17
    memberPaulo Morgado13-Sep-06 13:17 
    GeneralRe: Not attaching headers Pin
    kryzchek13-Sep-06 13:48
    memberkryzchek13-Sep-06 13:48 
    GeneralRe: Not attaching headers Pin
    Paulo Morgado14-Sep-06 11:33
    memberPaulo Morgado14-Sep-06 11:33 
    GeneralRe: Not attaching headers Pin
    kryzchek14-Sep-06 12:23
    memberkryzchek14-Sep-06 12:23 
    QuestionSample project? Pin
    kryzchek13-Sep-06 8:26
    memberkryzchek13-Sep-06 8:26 
    AnswerRe: Sample project? Pin
    Paulo Morgado13-Sep-06 8:58
    memberPaulo Morgado13-Sep-06 8:58 
    GeneralRe: Sample project? Pin
    kryzchek13-Sep-06 9:03
    memberkryzchek13-Sep-06 9:03 
    GeneralRe: Sample project? Pin
    Paulo Morgado13-Sep-06 11:45
    memberPaulo Morgado13-Sep-06 11:45 
    GeneralRe: Sample project? Pin
    kryzchek13-Sep-06 11:56
    memberkryzchek13-Sep-06 11:56 
    QuestionWhat server side changes we need for iis 5.0,5.1 and in xp Pin
    Achyutha20-Feb-06 0:58
    memberAchyutha20-Feb-06 0:58 
    AnswerRe: What server side changes we need for iis 5.0,5.1 and in xp Pin
    Paulo Morgado20-Feb-06 1:13
    memberPaulo Morgado20-Feb-06 1:13 
    GeneralCode Licencing Pin
    Ajith Kumar Balram17-Feb-06 0:30
    memberAjith Kumar Balram17-Feb-06 0:30 
    GeneralRe: Code Licencing Pin
    Paulo Morgado17-Feb-06 2:27
    memberPaulo Morgado17-Feb-06 2:27 
    GeneralDoes not work, help! Pin
    aruan3-Feb-06 22:10
    memberaruan3-Feb-06 22:10 
    GeneralRe: Does not work, help! Pin
    Paulo Morgado5-Feb-06 10:38
    memberPaulo Morgado5-Feb-06 10:38 
    GeneralHTTP compression in the .NET Framework 2.0 Pin
    Paulo Morgado13-Jan-06 11:51
    memberPaulo Morgado13-Jan-06 11:51 
    General.NET 2.0 no dependancy on sharpziplib Pin
    Ashley van Gerven8-Jan-06 22:28
    memberAshley van Gerven8-Jan-06 22:28 

    General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

    Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

    Permalink | Advertise | Privacy | Terms of Use | Mobile
    Web02 | 2.8.170525.1 | Last Updated 6 Jan 2006
    Article Copyright 2006 by Paulo Morgado
    Everything else Copyright © CodeProject, 1999-2017
    Layout: fixed | fluid