Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata