.NET proxy configuration

C# HttpClient Proxy: Authentication and Working Examples

Configure a C# HttpClient proxy with HttpClientHandler, WebProxy, secure credentials, timeouts, cancellation, and response checks. The examples keep one client per proxy configuration and separate connection errors from HTTP responses.

Quick answer: create a WebProxy, assign it to HttpClientHandler.Proxy, set UseProxy = true, then construct HttpClient with that handler. Read credentials from a protected configuration source, reuse the client for requests that share the same proxy, set explicit timeouts, and inspect both exceptions and HTTP status codes.

Basic C# HttpClient proxy example

Microsoft documents HttpClientHandler.Proxy as the IWebProxy used by the handler. An explicitly assigned proxy overrides applicable default system proxy settings. The property is unavailable on some platforms, including browser-hosted .NET, so confirm the deployment target.

using System.Net;
using System.Net.Http;

var proxy = new WebProxy(new Uri("http://proxy.example.net:8080"));

using var handler = new HttpClientHandler
{
    Proxy = proxy,
    UseProxy = true
};

using var client = new HttpClient(handler)
{
    Timeout = TimeSpan.FromSeconds(30)
};

using var response = await client.GetAsync("https://example.com/");
Console.WriteLine($"{(int)response.StatusCode} {response.ReasonPhrase}");

Replace the host and port with the endpoint supplied by the provider. Start with a harmless test URL, then test the real permitted destination. A successful TCP connection does not guarantee a successful target response.

Add proxy authentication securely

Do not hard-code production credentials in source control. Read them from environment variables, a secret store, or protected application configuration. The same principle applies to the environment-driven examples in our Python Requests proxy guide.

using System.Net;
using System.Net.Http;

string proxyHost = Environment.GetEnvironmentVariable("PROXY_HOST")
    ?? throw new InvalidOperationException("PROXY_HOST is missing");
string proxyUser = Environment.GetEnvironmentVariable("PROXY_USER")
    ?? throw new InvalidOperationException("PROXY_USER is missing");
string proxyPassword = Environment.GetEnvironmentVariable("PROXY_PASSWORD")
    ?? throw new InvalidOperationException("PROXY_PASSWORD is missing");

var proxy = new WebProxy(new Uri(proxyHost))
{
    Credentials = new NetworkCredential(proxyUser, proxyPassword)
};

using var handler = new HttpClientHandler
{
    Proxy = proxy,
    UseProxy = true
};

using var client = new HttpClient(handler);
using var response = await client.GetAsync("https://example.com/");
response.EnsureSuccessStatusCode();

If the provider uses source-IP authorization, the proxy may not need username/password credentials, but the machine’s public source IP must be authorized. Confirm the model before changing code.

Use cancellation and classify failures

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(20));

try
{
    using var response = await client.GetAsync(
        "https://example.com/health",
        HttpCompletionOption.ResponseHeadersRead,
        cts.Token);

    Console.WriteLine($"HTTP {(int)response.StatusCode}");
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
    Console.Error.WriteLine("The request exceeded the operation timeout.");
}
catch (HttpRequestException ex)
{
    Console.Error.WriteLine($"Connection or HTTP failure: {ex.Message}");
}

A timeout can originate from DNS, the proxy connection, TLS negotiation, the target, or local resource pressure. An HTTP 407 Proxy Authentication Required points to proxy credentials or authorization. A 403 or 429 from the destination means the route worked but the target declined or limited the request.

Reuse HttpClient correctly

Microsoft’s HttpClient guidelines recommend reuse to avoid unnecessary connection-pool churn. Create one client for requests that share the same handler and proxy configuration. Do not construct and dispose a new client for every request in a high-volume loop.

Because the handler owns the connection pool and proxy settings, use a separate handler/client when you genuinely need a different fixed proxy. Bound the lifetime through an application-level service or IHttpClientFactory design. Do not mutate the handler after requests have started.

Build a small proxy client factory

using System.Net;
using System.Net.Http;

static HttpClient CreateProxyClient(
    Uri proxyUri,
    string username,
    string password)
{
    var handler = new HttpClientHandler
    {
        UseProxy = true,
        Proxy = new WebProxy(proxyUri)
        {
            Credentials = new NetworkCredential(username, password)
        }
    };

    return new HttpClient(handler, disposeHandler: true)
    {
        Timeout = TimeSpan.FromSeconds(30)
    };
}

The caller owns the returned client and should reuse it for the intended lifetime. When a proxy must be retired, stop assigning new work, let active requests finish, then dispose its client.

Verify the exit IP

Before calling a business endpoint, make one request to an IP-check service and compare it with the purchased proxy. You can also verify manually with the Proxy Tester and IP Location Checker. Never log credentials or full authenticated proxy URLs.

using var response = await client.GetAsync("https://api.ipify.org?format=json");
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);

HTTP and SOCKS considerations

HttpClientHandler commonly works with HTTP proxies. SOCKS support depends on the .NET version, platform, handler implementation, and URI scheme. Do not assume a provider’s SOCKS endpoint can be passed to every application unchanged. Review the application and runtime documentation, then compare our HTTP vs SOCKS guide. When HTTP is supported, see the HTTP proxies guide; for SOCKS-specific clients, see SOCKS proxies.

Troubleshooting C# proxy errors

407 Proxy Authentication Required

Confirm username/password, source-IP authorization, and whether credentials belong on the proxy rather than the destination request. Check for extra spaces introduced by configuration.

The request bypasses the proxy

Set UseProxy = true, assign Proxy before creating the client, and verify the exit IP. Review local bypass rules and platform limitations.

Requests time out under load

Reuse clients, reduce parallelism, set cancellation, and compare direct, proxy, and target latency. A small connection pool can be saturated by unbounded tasks.

One target fails while the IP check works

The target may reject the request or require different TLS, headers, cookies, or policy-compliant access. Respect the response; a working proxy is not proof of target permission.

C# proxy checklist

  • Confirm runtime and platform support.
  • Create the proxy before the handler and client.
  • Set UseProxy = true.
  • Load credentials from protected configuration.
  • Reuse one client per stable proxy configuration.
  • Set timeouts and cancellation.
  • Inspect status codes and exceptions separately.
  • Test the exit IP and the real destination.
  • Never log credentials.

C# HttpClient proxy FAQ

Where do I set the proxy in HttpClient?

Set an IWebProxy, commonly WebProxy, on HttpClientHandler.Proxy before constructing HttpClient.

Should I create a new HttpClient for every request?

No. Reuse clients for requests with the same handler and proxy configuration to avoid connection-pool churn.

How do I authenticate to the proxy?

Assign a NetworkCredential to WebProxy.Credentials, or use the provider’s documented source-IP authorization. Store secrets outside source code.

Why does the direct request work but the proxy request fail?

Check endpoint reachability, authentication, protocol, TLS, DNS, target response, and timeout. Test one layer at a time.

Test the endpoint before integrating it

Validate the proxy independently, add it to a reusable handler/client, and run a controlled target request with explicit timeout handling. More programming examples are available in our cURL proxy, Python proxy, Java proxy, and PHP proxy guides.

Scroll to Top