Ways to Customize your ASMX Client Proxy

Technorati Tags: ,

There have been several questions in the ASMX Web Services and XML Serialization forum about customizing the behavior of the proxy class generated by Add Web Reference or by WSDL.EXE.  Add Web Reference creates a class that derives from SoapHttpClientProtocol.  This class has several properties you can set directly if you wish to customize its behavior. See SoapHttpClientProtocol Properties for details, but some of these are:

 

Property

Description

AllowAutoRedirect

Allows you to specify whether to allow the server to automatically redirect your request.

ClientCertificates

Allows you to specify the certificates presented by the client to the server.

CookieContainer

Allows you to save cookies returned by the server and to send them back on subsequent requests.

Credentials

Allows you to specify the security credentials to be used in authenticating with the server.

EnableDecompression

Allows you to specify whether to do automatic decompression.

Proxy

Allows you to specify an Internet Proxy Server to be used.

RequestEncoding

Specifies the encoding to be used in the request.

Timeout

Specifies how long to wait for a response from a synchronous request.

Url

Specifies the URL to talk to. This is the most frequently used property, as it allows you to configure the particular web service to talk to.

Heavy-Duty Customization

When setting these properties is not adequate, you can go further. The generated class is a partial class. This means that you can create a part of your own to add overriding methods. For instance, if you needed to set the KeepAlive property of the HttpWebRequest being used to communicate with the server, the SoapHttpClientProtocol class has a virtual method named GetWebRequest which is meant to return the HttpWebRequest instance to be used.  You can override that method:

 

public partial class Service1
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest request = (HttpWebRequest) base.GetWebRequest(uri);
        request.KeepAlive = true;
        return request;
    }
}

This technique allows you to change many aspects of the HttpWebRequest which will be used by the proxy class.
You can also override several other methods if you need specialized behavior. You can override:

  • GetWebResponse – given the WebRequest, returns the WebResponse to be used
  • GetReaderForMessage – given the response message, returns an XmlReader initialized to read the message.
  • GetWriterForMessage – given the request message, returns an XmlWriter initialized to write the message.
  • Abort – aborts an asynchronous web service request
  • Dispose – disposes of any unmanaged objects or objects that implement IDisposable

This provides a fair amount of flexibility in customizing the client.

This entry was posted in ASMX, Web Services. Bookmark the permalink.

Leave a comment