DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 13.7 Going Through a Proxy

Problem

Many companies have a web proxy that allows employees to access the Internet, while at the same time preventing outsiders from accessing the company's internal network. The problem is that to create an application that accesses the Internet from within your company, you must first connect to your proxy and then send information through it, rather than directly out to an Internet web server.

Solution

In order to get a HttpWebRequest successfully through a specific proxy server, we need to set up a WebProxy object with the settings to validate our specific request to a given proxy. Since this function is generic for any request, we create the AddProxyInfoToRequest method:

public static HttpWebRequest AddProxyInfoToRequest(HttpWebRequest httpRequest,
                          string proxyUri,
                          string proxyID,
                          string proxyPwd,
                          string proxyDomain)
{
    if(httpRequest != null)
    {
        // create the proxy object
        WebProxy proxyInfo = new WebProxy( );
        // add the address of the proxy server to use
        proxyInfo.Address = new Uri(proxyUri);
        // tell it to bypass the proxy server for local addresses
        proxyInfo.BypassProxyOnLocal = true;
        // add any credential information to present to the proxy server
        proxyInfo.Credentials = new NetworkCredential(proxyID,
                                                         proxyPwd,
                                                         proxyDomain);
        // assign the proxy information to the request
        httpRequest.Proxy = proxyInfo;
    }
    // return the request
    return httpRequest;
}

If all requests are going to go through the same proxy, you can use the static Select method on the GlobalProxySelection class to set up the proxy settings for all WebRequests, like so:

Uri proxyURI = new Uri("http://webproxy:80");
GlobalProxySelection.Select = new WebProxy(proxyURI);

Discussion

AddProxyInfoToRequest takes the URI of the proxy and creates a Uri object, which is used to construct the WebProxy object. The WebProxy object is set to bypass the proxy for local addresses and then the credential information is used to create a NetworkCredential object. The NetworkCredential object represents the authentication information necessary for the request to succeed at this proxy and is assigned to the WebProxy.Credentials property. Once the WebProxy object is completed, it is assigned to the Proxy property of the HttpWebRequest and the request is ready to be submitted.

See Also

See the "WebProxy Class," "NetworkCredential Class," and "HttpWebRequest Class" topics in the MSDN documentation.

    [ Team LiB ] Previous Section Next Section