Friday, May 24, 2013

Add gzip and/or deflate decompression to C# SOAP web service client

If your SOAP web service supports gzip or deflate compression, then you can enable corresponding decompression in C# web service client.

C# web service proxies normally has SoapHttpClientProtocol base class. This class internally uses HttpWebRequest class that supports automatic deflate and gzip decompression.

By default it is turned off. To enable it, set HttpWebRequest.AutomaticDecompression property to DecompressionMethods.Deflate | DecompressionMethods.GZip value.

To access AutomaticDecompression property of SoapHttpClientProtocol class, you need to inherit from your web service proxy class and override GetWebRequest method.

...

// This source code was auto-generated by wsdl, Version=2.0.50727.3038.
public partial class MyWebServiceProxy : System.Web.Services.Protocols.SoapHttpClientProtocol {
...
}

...

public class MyWebServiceProxyGzip : MyWebServiceProxy
{
    protected override System.Net.WebRequest GetWebRequest(Uri uri)
    {
        WebRequest webRequest = base.GetWebRequest(uri);
        HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

        if (httpWebRequest != null)
        {
            httpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        }

        return webRequest;
    }
}

...

    public void ReadUserInformation(String userName)
    {
        MyWebServiceProxyGzip myWebServiceProxyGzip = new MyWebServiceProxyGzip()
        {
            Url = "http://myservice.mydomain.com/WebService.aspx"
        };

        UserInformation userInformation = myWebServiceProxyGzip.GetUserInformation(userName);
    }

2 comments: