System.Net.IWebProxy.GetProxy Method

Returns the URI that the WebRequest object should use to connect to an Internet resource.

Declaration

public Uri GetProxy (Uri destination);

Parameters

  • destination: A Uri that identifies the Internet resource to connect to.

Returns

  • A Uri object that contains the proxy server to use.

Remarks

The GetProxy method is called by the WebRequest class to obtain the URI of the proxy server that should be used to access the specified Internet resource.

If no proxy server is required, the method should return the same destination URI.

Implementations of IWebProxy can use various strategies to determine the proxy, such as reading configuration files, querying environment variables, or using automatic proxy detection.

Example

using System;
using System.Net;

public class Example
{
    public static void Main(string[] args)
    {
        // Assume you have a custom proxy implementation
        IWebProxy customProxy = new MyCustomProxy();
        Uri originalUri = new Uri("http://www.contoso.com");

        Uri proxyUri = customProxy.GetProxy(originalUri);

        Console.WriteLine($"Original URI: {originalUri}");
        Console.WriteLine($"Proxy URI: {proxyUri}");

        // You can then use this proxyUri to configure your WebRequest
        WebRequest request = WebRequest.Create(originalUri);
        request.Proxy = customProxy; // Or set it directly if WebRequest uses it
    }
}

// A simple placeholder for a custom proxy implementation
public class MyCustomProxy : IWebProxy
{
    public ICredentials Credentials { get; set; }

    public Uri GetProxy(Uri destination)
    {
        Console.WriteLine($"MyCustomProxy: Determining proxy for {destination}");
        // In a real scenario, you would implement logic here
        // For demonstration, we'll just return a fixed proxy or the original URI
        if (destination.Host.Contains("contoso"))
        {
            return new Uri("http://my.proxyserver.com:8080");
        }
        return destination; // No proxy needed for other destinations
    }

    public bool IsBypassed(Uri host)
    {
        // Basic bypass logic
        return host.IsLoopback || host.Host.StartsWith("192.168.");
    }
}
                    

Requirements

Namespace: System.Net

Assembly: System (in System.dll)