.NET proxy configuration
C# HttpClient Proxy: Authentication and Working Examples
Configure a C# HttpClient proxy with 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 the handler’s Proxy property, 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.
Configure WebProxy on a .NET HTTP handler
The complete .NET 8+ console example uses SocketsHttpHandler to set a connection timeout separately from the request timeout. Create a console project, then replace its Program.cs with the example.
dotnet new console -o ProxyCheck -f net8.0
#nullable enable
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public static class ProxyCheck
{
public static async Task<int> Main(string[] args)
{
string proxyUrl = Environment.GetEnvironmentVariable("PROXY_URL")
?? throw new InvalidOperationException("Set PROXY_URL");
if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out Uri? endpoint)
|| endpoint.Scheme != "http" || endpoint.UserInfo.Length != 0)
{
throw new ArgumentException("Use an http:// proxy URL without credentials");
}
string? user = Environment.GetEnvironmentVariable("PROXY_USER");
string? password = Environment.GetEnvironmentVariable("PROXY_PASSWORD");
if ((user is null) != (password is null))
{
throw new InvalidOperationException("Supply both proxy credentials or neither");
}
var proxy = new WebProxy(endpoint);
if (user is not null && password is not null)
{
proxy.Credentials = new NetworkCredential(user, password);
}
var handler = new SocketsHttpHandler
{
UseProxy = true,
Proxy = proxy,
ConnectTimeout = TimeSpan.FromSeconds(5),
AllowAutoRedirect = false
};
using var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(15)
};
var target = new Uri(args.Length == 0 ? "https://api64.ipify.org" : args[0]);
try
{
using var response = await client.GetAsync(target);
Console.WriteLine($"HTTP {(int)response.StatusCode}");
if (!response.IsSuccessStatusCode)
{
return 1;
}
Console.WriteLine((await response.Content.ReadAsStringAsync()).Trim());
return 0;
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("Request timed out or was canceled");
return 1;
}
catch (HttpRequestException error)
{
Console.Error.WriteLine($"Request failed: {error.HttpRequestError}");
return 1;
}
}
}
Set PROXY_URL to your HTTP proxy endpoint, for example http://proxy.example.net:8080. Inject PROXY_USER and PROXY_PASSWORD from protected configuration for an authenticated endpoint. Leave both unset when a source-IP allowlist grants access.
dotnet run --project ProxyCheck
The default destination returns the observed public IP as plain text. To use a diagnostic endpoint you control, add -- and its URL to the run command. This client disables redirects so you can see the first response.
How HttpClient chooses a proxy
- Explicit proxy. Set
UseProxy = trueand assign aWebProxytoSocketsHttpHandler.ProxyorHttpClientHandler.Proxybefore constructing the client. Review bypass rules on that proxy object for the destination URI. - Runtime default. With
UseProxy = trueandProxy = null, modern .NET usesHttpClient.DefaultProxy. Its default settings can come from the process environment or the operating system. CheckHTTP_PROXY,HTTPS_PROXY,ALL_PROXYandNO_PROXYin the process that runs the application. - Direct comparison. Set
UseProxy = falseon a separate handler and use that client to compare the same permitted URL over a direct connection.
For an explicit WebProxy, call IsBypassed with the actual destination URI to inspect the object’s bypass decision. See Microsoft’s HttpClient.DefaultProxy reference for platform and environment behavior.
Set proxy credentials on WebProxy
WebProxy.Credentials handles proxy authentication. The destination API’s Authorization header belongs on its own request. The example takes credentials separately from the proxy URL and reports the runtime’s error category without logging the exception message or credentials. See Microsoft’s WebProxy credentials reference and our Python Requests sessions and environment guide.
For an IP-authorized proxy, confirm the public source IP of the machine running the program. An HTTPS destination still uses an http:// proxy URL when the connection to the proxy itself uses plain HTTP. An HTTPS CONNECT tunnel protects the traffic to the destination after the tunnel opens. Basic credentials sent to a plain HTTP proxy are outside that TLS connection.
Use cancellation and classify failures
The program allows five seconds to establish a connection and fifteen seconds for the request. Timeouts can originate in DNS, the proxy connection, TLS negotiation or the destination. The default GetAsync call buffers the response. For streaming, pass a cancellation token through response-body reads as well.
HTTP forwarding can return 407 as a response. A 407 during HTTPS CONNECT can surface as HttpRequestException with HttpRequestError.ProxyTunnelError before you get a destination response. Check the proxy challenge and credentials. A TLS handshake failure is a separate category. A 401, 403 or 429 from the destination calls for checking its authentication, access policy or rate limit.
Reuse HttpClient without changing proxy settings mid-session
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.
When to use separate clients
Give each fixed proxy configuration its own handler and client. When an endpoint is retired, stop giving its client new work before disposing it. For a service with long-lived pools, choose a lifetime that fits DNS and endpoint changes.
Verify the exit IP
Compare the IP printed by the console example with your provider’s expected egress address from the same machine or container that will make the requests. Use the Proxy Tester and IP Location Checker for independent checks, then make a read-only call to the intended destination.
Example verification. Compiled with Roslyn and ran on .NET 10.0.14 for Windows. Six local checks used synthetic credentials and a loopback proxy. They covered HTTP Basic, a bad password, an origin challenge, a no-password route, a rejected CONNECT tunnel, and rejection of an untrusted TLS certificate after authenticated CONNECT.
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 Requests setup, Java proxy, Rust proxy, and PHP proxy guides.
