Programming Pluggable Protocols

The abstract WebRequest and WebResponse classes provide the base for pluggable protocols. By deriving protocol-specific classes from WebRequest and WebResponse, an application can request data from an Internet resource and read the response without specifying the protocol being used.

Before you can create a WebRequest, you must register its Create method. Use the static RegisterPrefix method of WebRequest to register a WebRequest descendant to handle a set of requests to a particular Internet scheme, to a scheme and server, or to a scheme, server, and path. The following code example shows how to register an FtpWebRequest that is defined elsewhere. In this example, FtpWebRequestCreator is the object that implements the Create method that returns the FtpWebRequest object.

The following code example assumes that you have written additional code to handle the FTP protocol.

WebRequest.RegisterPrefix("ftp", new FtpWebRequestCreator());
WebRequest req = WebRequest.Create("");
[Visual Basic]WebRequest.RegisterPrefix("ftp", New FtpWebRequestCreator())
Dim req As WebRequest = WebRequest.Create("")

In most cases you will be able to send and receive data using the methods and properties of the WebRequest class. However, if you need to access protocol-specific properties, you can typecast a WebRequest to a specific derived-class instance, as in the following code example.

HttpWebRequest httpreq = 
   (HttpWebRequest) WebRequest.Create("");
[Visual Basic]Dim httpreq As HttpWebRequest = _
   CType(WebRequest.Create(""), HttpWebRequest)

To take advantage of pluggable protocols, your WebRequest descendants must provide a default request-and-response transaction that does not require protocol-specific properties to be set. For example, the HttpWebRequest class, which implements the WebRequest class for HTTP, provides a GET request and returns a WebResponse-derived HttpWebResponse that contains the stream returned from the Internet server.

See Also

Deriving from WebRequest | Deriving from WebResponse | Accessing the Internet