IWebProxy Interface

The System.Net.IWebProxy interface provides the methods and properties that are required to retrieve the proxy for a given Uri.

Overview
Syntax
Members
Example
See Also

Namespace

System.Net

Assembly

System.Net.Primitives.dll

Summary

Implementations of this interface can return a WebProxy object describing the proxy to use for a given request URI. The interface also allows you to specify how to handle requests that should bypass the proxy.

public interface IWebProxy
{
    ICredentials Credentials { get; set; }
    Uri GetProxy(Uri destination);
    bool IsBypassed(Uri host);
}

Properties

NameTypeDescription
CredentialsICredentialsGets or sets the credentials to submit to the proxy server for authentication.

Methods

SignatureDescription
Uri GetProxy(Uri destination)Returns the URI of the proxy for the specified destination.
bool IsBypassed(Uri host)Determines whether to bypass the proxy for the specified host.

Basic Usage

Below is a simple example of a class implementing IWebProxy and using it with HttpWebRequest:

using System;
using System.Net;

public class SimpleProxy : IWebProxy
{
    public ICredentials Credentials { get; set; }

    private readonly Uri _proxyUri;
    private readonly string[] _bypassList;

    public SimpleProxy(string proxyAddress, string[] bypassList = null)
    {
        _proxyUri = new Uri(proxyAddress);
        _bypassList = bypassList ?? new string[0];
    }

    public Uri GetProxy(Uri destination)
    {
        return IsBypassed(destination) ? destination : _proxyUri;
    }

    public bool IsBypassed(Uri host)
    {
        foreach (var bypass in _bypassList)
        {
            if (host.Host.EndsWith(bypass, StringComparison.OrdinalIgnoreCase))
                return true;
        }
        return false;
    }
}

// Usage
var proxy = new SimpleProxy("http://proxy.example.com:8080", new[] { "localhost", "127.0.0.1" });
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
request.Proxy = proxy;
request.Credentials = CredentialCache.DefaultCredentials;
using (var response = (HttpWebResponse)request.GetResponse())
{
    Console.WriteLine(response.StatusCode);
}