Configuring a proxy for HttpClient in C# and .NET
By the ProxyV4 Engineering Team · Updated:
To use a proxy with C# HttpClient, create a WebProxy with the proxy address, set its Credentials to a NetworkCredential, assign it to HttpClientHandler.Proxy (or SocketsHttpHandler.Proxy), and build the HttpClient from that handler. The proxy is a property of the handler, not of the request, so the way you create and reuse handlers decides how proxies behave across your app.
HttpClientHandler, WebProxy and credentials
Here is the base case as a top-level program for .NET 6 or later. It sends an HTTPS request through an authenticated HTTP proxy and prints the exit IP:
using System.Net;
var proxy = new WebProxy("http://203.0.113.10:8080")
{
Credentials = new NetworkCredential("USER", "PASS"),
BypassProxyOnLocal = false,
};
var handler = new HttpClientHandler
{
Proxy = proxy,
UseProxy = true,
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(20) };
string ip = await client.GetStringAsync("https://proxyv4.com/api/my-ip");
Console.WriteLine(ip);Keep the proxy address as http:// even though the target is HTTPS; the handler sends CONNECT and runs TLS to the website inside the tunnel. Credentials go on the WebProxy, not in the address. Because NetworkCredential holds the password as a plain string field, special characters such as @ or : need no escaping.
The handler answers the proxy's 407 challenge with the credentials you supplied, then reuses the authenticated connection. You do not need to add a Proxy-Authorization header yourself, and for HTTPS targets a header added to HttpRequestMessage would travel inside the tunnel, where the proxy cannot see it.
Handler lifetime decides proxy behavior
Since .NET Core 2.1, HttpClientHandler is a thin wrapper over SocketsHttpHandler, which owns the connection pool. Each handler keeps its own pool, its own proxy and its own authenticated connections. That has two practical consequences.
Do not create a handler per request
Building new HttpClient(new HttpClientHandler { ... }) inside a loop opens fresh connections to the proxy every time, repeats the 407 round trip and can exhaust sockets under load. Create one handler per proxy and keep it for the life of the process, or let IHttpClientFactory manage it.
Proxies are per handler, not per request
There is no supported way to change the proxy for one SendAsync call. Changing handler.Proxy after the first request throws an InvalidOperationException, because the handler's properties are locked once it starts sending. If you need several exit IPs, create several handlers or several named clients, one per IP. A custom IWebProxy can choose a proxy per destination URI through GetProxy(Uri), but it still cannot see the individual request.
IHttpClientFactory: a proxy per named client
In ASP.NET Core or a worker service, register one named client per proxy and configure its primary handler. The factory then pools and reuses the handler for you:
using System.Net;
var proxies = new Dictionary<string, string>
{
["worker-a"] = "http://203.0.113.10:8080",
["worker-b"] = "http://203.0.113.11:8080",
};
foreach (var (name, address) in proxies)
{
builder.Services.AddHttpClient(name, c => c.Timeout = TimeSpan.FromSeconds(20))
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
Proxy = new WebProxy(address)
{
Credentials = new NetworkCredential(
builder.Configuration["Proxy:User"],
builder.Configuration["Proxy:Pass"]),
},
UseProxy = true,
PooledConnectionLifetime = TimeSpan.FromMinutes(10),
})
.SetHandlerLifetime(Timeout.InfiniteTimeSpan);
}
// later, in a service:
// var client = httpClientFactory.CreateClient("worker-a");SocketsHttpHandler with PooledConnectionLifetime refreshes connections on its own, so the factory does not need to recycle the handler; that is why the example sets an infinite handler lifetime. Keep the proxy password in user secrets, environment configuration or a vault rather than in appsettings.json checked into source control.
Typed clients work the same way: AddHttpClient<PriceFetcher>().ConfigurePrimaryHttpMessageHandler(...) gives that one service its own exit IP while the rest of the app connects directly.
.NET SOCKS5 proxy support
From .NET 6, SocketsHttpHandler (and therefore HttpClientHandler) accepts SOCKS proxy URIs natively: socks4://, socks4a:// and socks5://. No NuGet package is required. Credentials still go on the WebProxy, and the handler uses them for SOCKS5 username and password authentication:
var handler = new SocketsHttpHandler
{
Proxy = new WebProxy("socks5://203.0.113.10:1080")
{
Credentials = new NetworkCredential("USER", "PASS"),
},
UseProxy = true,
};
using var client = new HttpClient(handler);
Console.WriteLine(await client.GetStringAsync("https://proxyv4.com/api/my-ip"));On .NET Framework 4.x and .NET 5 or earlier, SOCKS is not supported by HttpClient, and a socks5:// address fails with a NotSupportedException about the proxy scheme. Upgrade, or use the HTTP mode of your proxy. For which protocol to pick in the first place, see HTTP vs SOCKS5.
DefaultProxy, HTTP_PROXY and how they interact
A handler with no Proxy set uses the static HttpClient.DefaultProxy. On Linux and macOS that default is built from the HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY environment variables. On Windows, the environment variables are used when present and the system proxy settings otherwise.
The precedence is easy to state:
handler.Proxy = someProxyoverridesDefaultProxyand the environment for that handler only.handler.UseProxy = falsesends that handler's traffic directly, ignoring every proxy setting.HttpClient.DefaultProxy = new WebProxy(...)changes the default for all handlers that have no explicit proxy, so set it once at startup if you use it at all.- Credentials embedded as
http://USER:PASS@IP:PORTin an environment variable are picked up by the default proxy, which is handy in containers but places the password in the process environment.
Matching .NET workers to private IPv4 addresses
The named-client pattern above is useful when separate workers or tenants should never share an exit address: one worker per marketplace account, a background job that polls a partner API from a registered IP, or a scraper split across regions. A ProxyV4 private datacenter IPv4 maps onto it directly. Each IP has a single tenant for the whole term, arrives as one ip:port:user:pass line that splits into a WebProxy address and a NetworkCredential, and stays the same while active and after renewal.
Every paid proxy supports HTTP(S), and private IPv4 outside Vietnam and US static ISP proxies also support SOCKS5 with username and password, and you can enable both on the same port from the order page; switching modes can move the proxy to a new port, so copy the line again afterwards. Traffic on private IPv4 and static ISP is unmetered. IPs come from seven countries, with static ISP options in the United States and Vietnam, and live prices are per IP per month with a single-IP order allowed.
Skip it if your job needs a new IP per request, because rotating proxies are not on sale, or if you need IPv6 egress, which is a separate IPv6 proxy product. If your platform requires separate accounts, keep them legitimate and within that platform's rules; a dedicated IP separates traffic, it does not change those rules.
Diagnosing proxy failures in .NET
Most proxy problems in .NET surface as an HttpRequestException. The message, and on .NET 5 and later the HttpRequestError or inner SocketException, tells you the stage.
The proxy tunnel request failed with status code 407
For HTTPS targets the message reads The proxy tunnel request to proxy 'http://203.0.113.10:8080/' failed with status code '407'. The proxy rejected the login during CONNECT. Check that Credentials is set on the WebProxy actually assigned to this handler, not on the handler's own Credentials property, which is for the destination site. For plain HTTP targets you get a response with HttpStatusCode.ProxyAuthenticationRequired instead. More causes are listed in the 407 error guide.
Connection refused or timeouts
No connection could be made because the target machine actively refused it on Windows, or Connection refused (203.0.113.10:8080) on Linux, means the handler never reached the proxy: wrong IP, wrong port, or a port that moved after a protocol switch. A TaskCanceledException wrapping a TimeoutException means HttpClient.Timeout expired, often at the same stage. Confirm the port is open with the port checker.
The request went out without the proxy
If the exit IP is your own, check for UseProxy = false, a NO_PROXY entry matching the host, or a handler created somewhere else in the app. Logging the response of an IP echo endpoint at startup catches this before it matters.
Frequently asked questions
Can I set a proxy on a single HttpRequestMessage?
No. Proxies are configured on the handler, so create a separate handler or named client per proxy and send each request through the one you need.
Does HttpClient read user:pass from the WebProxy address?
Do not rely on it. Put the login in WebProxy.Credentials as a NetworkCredential, which works for HTTP and SOCKS5 proxies alike.
Which .NET versions support SOCKS5 in HttpClient?
.NET 6 and later, through SocketsHttpHandler and HttpClientHandler. Older runtimes need an HTTP proxy or a third-party library.
Can one ProxyV4 IP serve both HTTP and SOCKS5 clients?
Yes. Enable both modes on the order page and the same port accepts either, so a WebProxy with http:// or socks5:// works against the same line.
What if a proxy I bought does not connect at all?
Open a ticket from the dashboard; support runs 24/7. A proxy that fails for a technical reason, such as not connecting or showing the wrong location, is covered by the refund policy as account credit.
Give each .NET worker its own private IPv4
ProxyV4 private IPv4 proxies plug into `WebProxy` with a username and password over HTTP or SOCKS5, keep the same IP on renewal and never meter traffic. Order one IP, wire it into a named client, then scale.
See live prices