C# HttpClient Proxy: Authenticated Requests and SOCKS5
Send C# HttpClient requests through an authenticated proxy, switch to SOCKS5, verify the exit IP and handle 407s and timeouts.
To send a C# HttpClient request through an authenticated proxy, create a WebProxy with the proxy's http://HOST:PORT, put the username and password in its Credentials as a NetworkCredential, set it as the Proxy of a SocketsHttpHandler (or HttpClientHandler) with UseProxy = true, and build the HttpClient from that handler. For an https:// target .NET opens a CONNECT tunnel through the proxy by itself and verifies the target's certificate through it. For SOCKS5, change the scheme to socks5:// and nothing else: SocketsHttpHandler has spoken SOCKS4, SOCKS4a and SOCKS5, with username and password authentication, since .NET 6.
Every example on this page was compiled and run on December 4, 2026 on .NET 8.0.34, 9.0.23 and 10.0.15 (Linux). The refusal output shown is what those runs printed against Node4's rotating datacenter gateway; the success paths were run against a local proxy that logged every byte .NET sent. In the output below, the direct address of the test machine is replaced with a documentation address.
TL;DR
NetworkCredentialtakes the username and password verbatim. Auser:pass@inside theWebProxyaddress is ignored, not decoded: the request goes out with no credential and fails with a 407. The only URL .NET reads a credential from is a proxy environment variable (HTTP_PROXY,HTTPS_PROXYorALL_PROXY, used whenProxyis left unset), and there it is percent-decoded.- A wrong credential on an HTTPS target is not a 407 response in C#:
GetAsyncthrowsHttpRequestExceptionwithHttpRequestError.ProxyTunnelError, the 407 is in the message, andStatusCodeisnullon .NET 8 and407on .NET 9 and 10. - A SOCKS5 refusal is the same
ProxyTunnelErrorwith an inner exception whose message isSOCKS server failed to connect to the destination.; the scheme issocks5://, andsocks5h://throwsNotSupportedException. - An exit is picked per connection: once for each
CONNECTtunnel, once for each SOCKS5 connection, and on the HTTP port once for each plainhttp://request, because the gateway forwards every plain request over its own connection to an exit. A pooled tunnel keeps its exit, and the pool key ignores the credential, so a sticky session needs its own handler.
Before you start
- .NET 6 or later. SOCKS support arrived in .NET 6 (
SocketsHttpHandler, announced in Microsoft's .NET 6 networking improvements);HttpRequestError, which the code below branches on, arrived in .NET 8. On .NET Framework,HttpClientHandleris a different implementation that speaks no SOCKS and surfaces proxy failures differently; only the HTTP path withWebProxyandNetworkCredentialcarries over. - Your proxy username and password. Node4 keeps one credential per account under Auth & IP Access in Account Settings (a paid account may add up to 5 sets, one per service if you like), and the gateway accepts it for any product the account holds a plan for. A username you choose is letters, digits and underscores; the dashboard refuses a hyphen, because the gateways read
-country-and-session-segments out of the username. A username Node4 minted for you (node4_<id>_<8 characters>) can contain a hyphen, which is harmless, since a segment starts only at a key the gateway recognizes. - Something you may legitimately fetch over HTTPS. Below that is
https://node4.io/api/tools/ip, Node4's echo endpoint, whose JSON names the connecting address and its country. The residential gateway does not open node4.io itself (it answers 403), so point a residential test at a third-party echo (https://ipinfo.io/jsonreturns the same two fields). - A plan for the gateway you are pointing at. A free account has 3 static shared datacenter proxies with 1 GB a month, HTTP(S) only: enough to prove the
http://path with a host and port copied from Proxies. A free credential sent to a rotating or residential gateway gets a 407, and a free SOCKS5 connection is refused.
The examples use the Rotating Datacenter gateway. The other gateway products take the same code with a different host and port; put http:// in front of the HTTP endpoint and socks5:// in front of the SOCKS5 one to make the WebProxy address:
| Product | HTTP endpoint | SOCKS5 endpoint |
|---|---|---|
| Rotating Datacenter, billed by the gigabyte | gw-rotating_datacenter.node4.io:8083 | gw-rotating_datacenter.node4.io:1083 |
| Rotating Unmetered, priced by concurrent connections | gw-rotating_unmetered.node4.io:8084 | gw-rotating_unmetered.node4.io:1084 |
| Residential, billed by the gigabyte | gw-residential.node4.io:8082 | gw-residential.node4.io:1082 |
| Shared and dedicated datacenter, per proxy per month | the address beside each proxy on Proxies | the SOCKS5 port on the Connect card |
Both rotating products draw one exit pool, in the US, Italy and Spain; what differs is the meter, by the gigabyte on Rotating Datacenter or by concurrent connections on Rotating Unmetered.
The working request through an authenticated HTTP proxy
Create a console project (dotnet new console) and replace Program.cs with this. It builds the gateway username, configures the handler, fetches the echo endpoint once direct and three times through the proxy, and reduces whatever .NET reports to one Cause string that is safe to log and easy to branch on. The password never reaches the output.
using System.Net;
using System.Text.Json;
using System.Text.RegularExpressions;
// Environment: NODE4_PROXY_URL http://gw-rotating_datacenter.node4.io:8083
// or socks5://gw-rotating_datacenter.node4.io:1083
// NODE4_PROXY_USER, NODE4_PROXY_PASS
const string Echo = "https://node4.io/api/tools/ip";
string? proxyUrl = Environment.GetEnvironmentVariable("NODE4_PROXY_URL");
string user = Environment.GetEnvironmentVariable("NODE4_PROXY_USER") ?? "";
string pass = Environment.GetEnvironmentVariable("NODE4_PROXY_PASS") ?? "";
using HttpClient direct = Proxy.Client(null, "", "");
Console.WriteLine($"direct: {Proxy.Line(await Proxy.Fetch(direct, Echo))}");
if (proxyUrl is null) return;
var cases = new (string Label, string Username, string Url)[]
{
("proxied, HTTPS target", Proxy.Username(user), Echo),
("proxied, HTTP target", Proxy.Username(user), "http://httpbin.org/ip"),
("sticky session job4182", Proxy.Username(user, null, "job4182"), Echo),
};
foreach (var (label, username, url) in cases)
{
using HttpClient client = Proxy.Client(new Uri(proxyUrl), username, pass);
Console.WriteLine($"{label,-24} {Proxy.Line(await Proxy.Fetch(client, url))}");
}
static class Proxy
{
/// Targeting rides in the username. Order: base, -country-xx, -session-ID. The gateway starts a
/// segment only at a key it recognizes, so the base is checked for a stray key, not for hyphens:
/// a username Node4 minted for you (node4_<id>_<8 characters>) may legitimately contain one.
public static string Username(string baseUser, string? country = null, string? session = null)
{
if (!Regex.IsMatch(baseUser, "^[A-Za-z0-9_-]+$") || Regex.IsMatch(baseUser, "-(session|country|city|state|asn)-")) throw new ArgumentException("base username: letters, digits, underscores and hyphens only, with no targeting segment inside it");
if (country is not null && !Regex.IsMatch(country, "^[a-z]{2}$")) throw new ArgumentException("country: two lowercase letters, such as us, it or es");
if (session is not null && !Regex.IsMatch(session, "^[A-Za-z0-9]{1,32}$")) throw new ArgumentException("session: 1 to 32 letters and digits");
return baseUser + (country is null ? "" : "-country-" + country) + (session is null ? "" : "-session-" + session);
}
/// One HttpClient over one SocketsHttpHandler, so one connection pool, for one proxy and credential.
/// proxyUri is http://HOST:PORT or socks5://HOST:PORT; null goes direct and ignores the proxy environment variables too.
public static HttpClient Client(Uri? proxyUri, string username, string password)
{
var handler = new SocketsHttpHandler
{
UseProxy = proxyUri is not null,
Proxy = proxyUri is null ? null : new WebProxy(proxyUri)
{
BypassProxyOnLocal = false, // "node4.io" has a dot, but keep local names proxied too
Credentials = new NetworkCredential(username, password), // taken verbatim: no percent-encoding
},
AllowAutoRedirect = false, // inspect a redirect before the next request leaves
ConnectTimeout = TimeSpan.FromSeconds(10), // reaching the proxy and getting the tunnel open
PooledConnectionLifetime = TimeSpan.FromMinutes(2), // re-resolve the gateway's DNS now and then
};
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) }; // the whole request, tunnel included
}
public record Result(string Cause, int Status, string Detail, string? Exit = null);
public static async Task<Result> Fetch(HttpClient client, string url)
{
try
{
using HttpResponseMessage resp = await client.GetAsync(url);
string body = await resp.Content.ReadAsStringAsync();
return Classify(resp, body);
}
catch (Exception ex) { return Classify(ex); }
}
/// A response arrived: on a plain-HTTP target it may be the gateway's own (407, or a 429/503/502 with the
/// gateway's markers); anything else is the target's. On an HTTPS target every response is the target's,
/// because a gateway refusal of the CONNECT never becomes a response (see Classify(Exception)).
static Result Classify(HttpResponseMessage resp, string body)
{
int status = (int)resp.StatusCode;
bool connLimit = resp.Headers.Contains("X-Node4-Conn-Limit");
bool stickyDown = resp.Headers.TryGetValues("X-Node4-Sticky", out var v) && v.Contains("unavailable");
// The gateway's own 502 bodies: "no exit available" (a country with no exits, or an empty pool)
// and "upstream error" (it tried up to three exits and none reached the target).
bool gatewayBody = body.StartsWith("no exit available") || body.StartsWith("upstream error");
string cause = status switch
{
407 => "proxy-auth",
429 when connLimit => "proxy-refused-429",
503 when stickyDown => "proxy-refused-503",
502 when gatewayBody => "proxy-refused-502",
>= 200 and < 300 => "ok",
_ => "target-http-" + status,
};
string? exit = null;
if (cause == "ok") { try { var root = JsonDocument.Parse(body).RootElement; exit = (root.TryGetProperty("ip", out var ip) ? ip : root.GetProperty("origin")).GetString(); } catch (JsonException) { } }
return new Result(cause, status, body.Length > 70 ? body[..70] : body.Trim(), exit);
}
/// No response: the exception type and HttpRequestError say which hop failed.
static Result Classify(Exception ex) => ex switch
{
// The gateway answered the CONNECT with something other than 200. The status is only in the message on
// .NET 8 (HttpRequestException.StatusCode is null there); .NET 9 and 10 also set StatusCode.
HttpRequestException { HttpRequestError: HttpRequestError.ProxyTunnelError, InnerException: null } h
=> TunnelStatus(h.Message) is int s and not 0
? new Result(s == 407 ? "proxy-auth" : "proxy-refused-" + s, s, h.Message)
: new Result("proxy-tunnel", 0, h.Message),
// SOCKS5: the inner exception (SocksException, an internal type you cannot name) carries the refusal.
// Reply 2 covers every 407 cause and the connection ceiling alike.
HttpRequestException { HttpRequestError: HttpRequestError.ProxyTunnelError, InnerException: { } inner }
=> new Result("socks5-refused", 0, inner.Message),
HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError } h
=> new Result("proxy-unreachable", 0, h.Message), // bad host, bad port, firewall
HttpRequestException { HttpRequestError: HttpRequestError.SecureConnectionError } h
=> new Result("tls", 0, h.InnerException?.Message ?? h.Message), // the target's certificate did not verify
TaskCanceledException { InnerException: TimeoutException te } => new Result("timeout", 0, te.Message), // HttpClient.Timeout or ConnectTimeout
TaskCanceledException => new Result("canceled", 0, ex.Message), // your own CancellationToken
HttpRequestException h => new Result("http-" + h.HttpRequestError, 0, h.Message),
_ => new Result("error-" + ex.GetType().Name, 0, ex.Message),
};
static int TunnelStatus(string message)
{
var m = Regex.Match(message, @"status code '(\d{3})'");
return m.Success ? int.Parse(m.Groups[1].Value) : 0;
}
public static string Line(Result r) => r.Cause == "ok"
? $"ok exit={r.Exit}"
: $"{r.Cause} status={r.Status} detail={r.Detail}";
}Set NODE4_PROXY_URL, NODE4_PROXY_USER and NODE4_PROXY_PASS in the environment (from your secret store in production) and run dotnet run.
Expected result: the direct line prints your own public address, and the three proxied lines print ok with a different address (the second from httpbin's origin field), from an exit in the US, Italy or Spain. With a credential the gateway does not accept, the run prints exactly this, identically on .NET 8, 9 and 10:
direct: ok exit=203.0.113.24
proxied, HTTPS target proxy-auth status=407 detail=The proxy tunnel request to proxy 'http://gw-rotating_datacenter.node4.io:8083/' failed with status code '407'."
proxied, HTTP target proxy-auth status=407 detail=proxy authentication required
sticky session job4182 proxy-auth status=407 detail=The proxy tunnel request to proxy 'http://gw-rotating_datacenter.node4.io:8083/' failed with status code '407'."The first and third targets were HTTPS, so .NET asked the proxy for a CONNECT tunnel, the proxy answered 407, and GetAsync threw an HttpRequestException whose HttpRequestError is ProxyTunnelError. There is no HttpResponseMessage at all. The 407 lives in the exception message (the stray " at its end is in .NET's own resource string) and, from .NET 9 on, in HttpRequestException.StatusCode; on .NET 8 that property is null for a tunnel failure, which is why Classify reads the message. GetStringAsync sees the same exception.
On the plain http:// target the 407 arrives as a normal response: body proxy authentication required, header Proxy-Authenticate: Basic realm="node4". GetStringAsync on it throws HttpRequestException with StatusCode 407 and the message Response status code does not indicate success: 407 (Proxy Authentication Required).
Classify reads the connect failure before the target status for a reason. Once the tunnel is open, every status after that, 502 included, is the target speaking through the tunnel; a plain-HTTP 502 is attributed to the gateway only when its body starts with one of the gateway's own texts, no exit available (a country with no exits) or upstream error (no exit reached the target).
What each setting does
| Setting | What it does | Why it is set this way |
|---|---|---|
WebProxy(Uri) | Proxy host, port and scheme. http:// for the HTTP port, socks5:// for the SOCKS5 port | new WebProxy("host", port) and a scheme-less "host:port" both produce http://host:port/. https:// means TLS to the proxy itself, which the gateways do not offer |
WebProxy.Credentials | The proxy credential, verbatim | A user:pass@ in the address is not read: Credentials stays null and the request fails with a 407 (the next section has the listener log) |
UseProxy = true, Proxy = ... | Use this proxy for every request of this handler | UseProxy is true by default with Proxy null, which means HttpClient.DefaultProxy: on Linux the HTTP_PROXY, HTTPS_PROXY, ALL_PROXY and NO_PROXY variables, on Windows and macOS those or the system settings. UseProxy = false goes direct whatever the environment says, which is what makes the direct line a fair comparison |
BypassProxyOnLocal = false | Proxy every host | With true, a hostname without a dot is sent direct |
AllowAutoRedirect = false | Return redirects instead of following them | Look at a Location before anything else leaves through the same exit |
ConnectTimeout | Time to get a usable connection: the TCP connect to the gateway plus the CONNECT or SOCKS5 exchange | Verified against a listener that accepted the connection and never answered: the request failed after exactly this long with A connection could not be established within the configured ConnectTimeout. Default: infinite |
HttpClient.Timeout | Time for the whole request, connection phase included | Default 100 seconds. Fires as TaskCanceledException with an inner TimeoutException; a CancellationToken of your own has no TimeoutException inside |
PooledConnectionLifetime | Close a connection after this long, even if busy, so the next request resolves DNS again | A long-lived HttpClient never re-resolves otherwise. Microsoft's HttpClient guidelines recommend it for every long-lived client |
| TLS to the target | Verified through the tunnel, as always | Left on. Setting ServerCertificateCustomValidationCallback to accept everything fixes nothing about the proxy; an HTTP proxy relays TLS bytes it cannot read |
HttpClientHandler or SocketsHttpHandler?
Either. HttpClientHandler on .NET Core and .NET 5 and later is a wrapper over SocketsHttpHandler, so new HttpClientHandler { Proxy = proxy, UseProxy = true } behaves identically for everything on this page, including SOCKS5 and the exception output (the run above was repeated with it). It lacks ConnectTimeout and the pooled-connection settings, which is the reason to prefer SocketsHttpHandler in new code.
SOCKS5: socks5://, which .NET resolves at the proxy
Switch the scheme and nothing else:
var proxy = new WebProxy("socks5://gw-rotating_datacenter.node4.io:1083")
{
Credentials = new NetworkCredential(username, password),
};Three differences from curl. The scheme is socks5://, not socks5h://: .NET accepts exactly http, https, socks4, socks4a and socks5, and anything else throws NotSupportedException: Only the 'http', 'https', 'socks4', 'socks4a' and 'socks5' schemes are allowed for proxies. on the first request. Second, there is no local-resolution variant to avoid: .NET's socks5:// already behaves like curl's socks5h://, sending the target hostname to the proxy (address type 3 in the SOCKS5 request; a local listener logged host=node4.io) so the exit resolves it, which is what you want for geo-fenced DNS. Only an address you wrote as a literal IP is sent as an IP. Third, authentication needs no extra setting: with Credentials set, .NET offers both "no authentication" and "username/password" in the SOCKS5 greeting and completes the RFC 1929 exchange when the proxy picks the latter; with Credentials null it offers "no authentication" only, which the gateway accepts from a whitelisted source address and otherwise refuses at the connect reply.
The username is parsed the same way on both ports, so -country- and -session- segments need no change for SOCKS5. Refusals look different. The same program, wrong credential, SOCKS5 port:
direct: ok exit=203.0.113.24
proxied, HTTPS target socks5-refused status=0 detail=SOCKS server failed to connect to the destination.
proxied, HTTP target socks5-refused status=0 detail=SOCKS server failed to connect to the destination.
sticky session job4182 socks5-refused status=0 detail=SOCKS server failed to connect to the destination.There is no status line or header in SOCKS5. The gateway completes the username and password exchange, then answers the connect request with a reply byte, and .NET surfaces that as HttpRequestException (ProxyTunnelError, message An error occurred while establishing a connection to the proxy tunnel.) wrapping a SocksException. Two details matter in code: SocksException is an internal type, so you cannot catch it by name and must match on HttpRequestError.ProxyTunnelError with a non-null InnerException, as Classify does; and .NET 10 appends the reply byte to the message (SOCKS server failed to connect to the destination. Received error code 0x02.), while .NET 8 and 9 do not.
The reply byte is the whole diagnosis. Reply 2 ("connection not allowed by ruleset") is what the gateway sends for anything that would be a 407 on the HTTP port, and also for a Rotating Unmetered account at its connection ceiling, so by itself it does not identify a bad credential. Reply 4 ("host unreachable") is a country with no exits, and also an exit that could not reach the target. Reply 1 is a sticky session the gateway could not pin. To find out why, send one request through the HTTP port, which answers with a status and a body. The port for every product is on SOCKS5 proxy setup.
Where does the credential go?
In WebProxy.Credentials, and nowhere else. Four places a C# developer puts a proxy credential, and what .NET does with each, checked against a local listener that logged the Proxy-Authorization header it received:
| Where you put it | What arrives at the proxy |
|---|---|
WebProxy.Credentials = new NetworkCredential(user, pass) | The exact strings. A password of p@ss:w%rd arrived as p@ss:w%rd. No encoding, ever |
new WebProxy("http://user:p%40ss@host:port") | Nothing. Credentials is null, the tunnel request carries no header, the proxy answers 407 and .NET gives up (The proxy tunnel request to proxy 'http://user:p%40ss@host:port/' failed with status code '407'.") |
HTTPS_PROXY=http://user:p%40ss%3Aw%25rd@host:port with Proxy unset | The credential, percent-decoded: p@ss:w%rd arrived. HTTP_PROXY (for http:// targets) and ALL_PROXY (for either, when the specific one is unset) are parsed the same way, and the lowercase spellings are read first. Microsoft's HttpClient documentation lists the variables and their precedence; NO_PROXY=node4.io made the echo request go direct |
request.Headers.ProxyAuthorization = new AuthenticationHeaderValue("Basic", ...) | On a plain http:// target, the header is sent with the first request and the 407 round trip is skipped. On an https:// target it is not sent on the CONNECT at all (the tunnel request is built internally), so it does nothing |
Every new tunnel costs a round trip. .NET never sends Basic credentials proactively on a CONNECT: each new tunnel is a CONNECT without a header, a 407 from the gateway, and a second CONNECT with Proxy-Authorization on the same TCP connection. The local listener logged exactly that pair for every tunnel on every .NET version. On a pooled connection that is paid once; on a worker that forces a fresh exit per request it is paid per request, and HttpClientHandler.PreAuthenticate does not change it, because .NET's pre-authentication applies to the target's WWW-Authenticate, not the proxy's.
How do you know the request went through the proxy?
By the exit address in an echo body, not by the status. Three checks, in order:
- Compare addresses. The
directline and the proxied lines must show different addresses. Nothing inHttpResponseMessagetells you the exit; only the body of an echo endpoint does. - Read the country. The
countryfield in the echo JSON belongs to the exit. Untargeted rotating datacenter traffic leaves from the US, Italy or Spain; add-country-itand the field readsIT, or the gateway refuses the request rather than quietly substituting another country. - Check the content, then the headers. A 200 can carry a consent page or a login form, so validate a field your parser needs before treating the response as data. The gateway's diagnostic headers,
X-Node4-Sticky(opened,held,none,unavailable) andX-Node4-Country(honored,unavailable,none), appear on plain-HTTP responses and on refusals made after authentication (a 407 carries neither), which is whereClassifyreads them. On an HTTPS target you cannot read them from C#: .NET consumes the gateway'sCONNECTresponse internally and hands you only the target's response. SOCKS5 carries neither header. So prove the exit and the country by the echo endpoint.
When does the exit IP change?
When a connection to an exit is made: each CONNECT tunnel, each SOCKS5 connection, and on the HTTP port each plain http:// request, which the gateway forwards over its own connection to an exit even when your client reused its connection to the gateway. SocketsHttpHandler pools connections, so after the first request to a host every further request to it rides the open tunnel and leaves from the same exit, for as long as the tunnel lives. The local listener counted it: three GetAsync calls on one client opened one tunnel. To get a new pick per request on a shared client, close the connection after each response:
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.ConnectionClose = true; // Connection: close, so the next request opens a new tunnel
using var response = await client.SendAsync(request);Three calls with that header opened three tunnels. PooledConnectionIdleTimeout is the gentler version: set to one second, a request after a pause of two and a half seconds opened a second tunnel while back-to-back requests shared one. Each new tunnel is a new pick from the pool, which can return an address you have had before, and each costs the 407 round trip above. How often the rotating IP changes has the full timing table.
Keeping one exit: sticky sessions
To keep one exit across many connections deliberately, put a session id in the username:
string username = Proxy.Username("USERNAME", null, "job4182"); // USERNAME-session-job4182
string username = Proxy.Username("USERNAME", "us", "job4182"); // USERNAME-country-us-session-job4182A rotating gateway keeps a session's exit for up to 30 minutes, counted from first assignment; activity does not extend the window, so a job that runs longer mints a fresh id when the old one ends. Any 1 to 32 letters and digits make an id, and ids are scoped to your credential. The country segment limits which exits qualify; the session segment fixes the pick. Sticky vs rotating sessions covers which jobs want one and what a mid-task exit change breaks.
A session needs its own handler. The connection pool is keyed by target host, port and proxy address, not by the proxy credential. Change proxy.Credentials to a new session username on a handler that already holds an open tunnel and the next request rides the old tunnel under the old session: the local listener logged a single CONNECT with -session-aaa across both requests of that experiment, and nothing with -session-bbb. Two handlers, one per session, opened two tunnels with two usernames. So build one SocketsHttpHandler (and HttpClient) per session, keep the set bounded, and dispose each when its job is done; the worker below does exactly that. MaxConnectionsPerServer caps tunnels per target host, not per proxy: six concurrent requests to one host with it set to two opened two tunnels, and requests to a second host would open their own.
Proxy.Username validates its inputs because the rotating gateway splits the username on known markers and has no notion of a misspelled one. USERNAME-sesion-x contains no recognized marker, so the whole string is treated as the username, no credential matches, and the answer is a 407. USERNAME-country-us-sesion-x is read as country US-SESION-X, a country with no exits, so a 502. USERNAME-session-x-contry-de is read as session x-contry-de with no country at all, and the request succeeds from an untargeted exit, the quiet failure the regular expressions above prevent. Each case is shown on the typo examples. Residential is a different parser: an unknown key is a 400 that names the key wherever it appears, residential sessions are best effort with a 30-minute ceiling and no minimum because the exit is a consumer device, and state, city and asn segments follow country and city targeting.
Instead of a credential you can whitelist your source address under Auth & IP Access; whitelisting is available on every Node4 product. From a whitelisted address a static datacenter proxy takes a request with Credentials left null. The rotating gateways (Rotating Datacenter and Rotating Unmetered) also accept the username with an empty password, new NetworkCredential(username, ""), so country and session segments keep working. The residential gateway wants no username and no password at all from a whitelisted address, which also means no targeting on that connection. Authentication compares the two modes.
IHttpClientFactory: one named client per proxy, not per request
using var client = new HttpClient(new HttpClientHandler { Proxy = ... }) inside a method that runs per request creates a handler, and a connection pool, per call; the closed sockets sit in TIME_WAIT until the OS runs out of ports. Microsoft's HttpClient guidelines give the two sanctioned shapes, a long-lived client with PooledConnectionLifetime set or short-lived clients from IHttpClientFactory, and add that more than one instance is "necessary for scenarios with multiple proxies". With the factory, a proxy is a named client, configured once:
builder.Services.AddHttpClient("rotating")
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
Proxy = new WebProxy("http://gw-rotating_datacenter.node4.io:8083")
{
Credentials = new NetworkCredential(user, pass),
},
UseProxy = true,
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionLifetime = TimeSpan.FromMinutes(2), // DNS refresh handled here...
})
.SetHandlerLifetime(Timeout.InfiniteTimeSpan); // ...so factory-level handler rotation is switched offfactory.CreateClient("rotating") then returns a cheap HttpClient over the shared handler, and a second registration ("residential", "direct") is a second pool with its own proxy. Two rules from Microsoft's IHttpClientFactory guide bite with proxies in particular. The number of named clients must be bounded ("don't derive the client name from unbounded input"), so a sticky session id can never be a client name; sessions are the worker's own small handler set below. And the factory's default handler lifetime is two minutes: unless you set it to infinite as above and let PooledConnectionLifetime do the DNS work, every two minutes a fresh handler means fresh tunnels, which on a rotating gateway means fresh exits for every client at once. The same guide notes that pooled handlers share a CookieContainer; a scraper that keeps cookies per exit should turn UseCookies off and manage them itself.
407, 502 and timeouts: what C# shows and what to change
Each failure as C# reports it, where the detail lives, and the fix. Keep the gateway's verdict and the target's verdict apart: a ProxyTunnelError is what the gateway said to CONNECT, and after the tunnel opens every status belongs to the target. A gateway 502 arrives the way a 407 does: a ProxyTunnelError whose message ends failed with status code '502'." on an HTTPS target, an ordinary response on a plain-HTTP one. It has two causes, a country with no exits and an exit that could not reach the target; on plain HTTP the body names which, on HTTPS the body is consumed with the CONNECT, so tell them apart by whether the username carries -country-, or by one request over the HTTP port.
What Fetch reports | Where the detail is | Cause | What to change |
|---|---|---|---|
proxy-auth, HttpRequestException, HttpRequestError.ProxyTunnelError, message ends status code '407'." | The message; StatusCode too from .NET 9 | The gateway did not accept the credential: a mistyped or rotated password, a stray character pasted in, a source address that no longer matches the whitelist, a free or expired account hitting a gateway, an exhausted allowance, or a typo in the first segment key after the username | Try the same credential with one curl line. curl succeeding means C# is not sending what you think (a user:pass@ in the WebProxy address does exactly that); curl failing too means the credential or the account, and the 407 guide lists what to check |
proxy-auth, status=407, body proxy authentication required | HttpResponseMessage on an http:// target | As above | As above |
proxy-refused-502, message ends status code '502'."; on plain HTTP a 502 whose body begins no exit available | The message, or the gateway's body on plain HTTP | The requested country has no exits in the pool, or a typo behind -country- turned the code into one that does not exist | Correct or remove the country segment; no number of retries changes the answer |
proxy-refused-502 with no -country- in the username; on plain HTTP a 502 whose body begins upstream error | The message, or the gateway's body on plain HTTP | The gateway tried up to three exits and none reached the target | Retry with backoff; if it persists, the target is refusing the exit range, and the credential is not involved |
target-http-502 (a response, on either target scheme, without the gateway's body) | resp.StatusCode | On HTTPS the tunnel was open, and on plain HTTP the gateway reached the target, so the 502 is the target's own | A target problem: wait and retry, or look at the target itself. Neither credential nor country is involved |
proxy-refused-503; on plain HTTP a 503 with X-Node4-Sticky: unavailable | The message, or the header on plain HTTP | No exit could be pinned for the session at that moment | Pause and retry, or remove -session- and let the exit rotate |
proxy-refused-429; on plain HTTP a 429 with X-Node4-Conn-Limit | The message, or the header on plain HTTP | A Rotating Unmetered account is at its connection ceiling, and idle pooled tunnels count toward it | Slow down, dispose idle handlers, reduce WORKERS, or buy a larger rung (connection limits) |
socks5-refused, inner message SOCKS server failed to connect to the destination. (Received error code 0x02. appended on .NET 10) | HttpRequestException.InnerException.Message | Every 407 cause, plus a Rotating Unmetered account at its connection ceiling (reply 2); a country with no exits, or an exit that could not reach the target (reply 4); a sticky session that could not be pinned (reply 1) | Send one request through the HTTP port instead, where the refusal has a status: 407 credential, 429 ceiling, 502 country or dead exit, 503 session. Back off until that answer is in |
socks5-refused, inner message Failed to authenticate with the SOCKS server. | Same | The RFC 1929 exchange itself was rejected | Correct the credential. Node4's gateways do not produce this message for a wrong password; they accept the exchange and answer the connect with reply 2 |
timeout, TaskCanceledException with inner TimeoutException A connection could not be established within the configured ConnectTimeout. | ex.InnerException | ConnectTimeout expired: the gateway was reachable but the CONNECT or SOCKS5 exchange never completed, or the TCP connect itself hung | A larger timeout does not repair a wrong port or a firewall; check the host and port against the table above |
timeout, TaskCanceledException with inner TimeoutException, message The request was canceled due to the configured HttpClient.Timeout of 30 seconds elapsing. | ex.Message | HttpClient.Timeout expired on the whole request, for example a target slow to answer through an open tunnel | Identify the stage first; the default is 100 seconds, so set it deliberately |
canceled, TaskCanceledException with no TimeoutException inside | ex.InnerException | Your own CancellationToken fired | Not a network fault |
proxy-unreachable, HttpRequestError.NameResolutionError, Name or service not known (host:port) | HttpRequestException.Message | Hostname typo | Check the host against the table above |
proxy-unreachable, HttpRequestError.ConnectionError, Connection refused (host:port) | Same | Wrong port, or an outbound firewall | Check the port |
error-NotSupportedException, Only the 'http', 'https', 'socks4', 'socks4a' and 'socks5' schemes are allowed for proxies. | The exception | A socks5h:// or other scheme copied from a curl command | Use socks5://; .NET resolves at the proxy anyway |
tls, HttpRequestError.SecureConnectionError | ex.InnerException | Certificate validation of the target failed | Look at the system clock and CA store first; never answer with an accept-all callback |
ok, wrong content | The body | A login form, cookie banner or anti-bot challenge came back with status 200 | Check for a marker your parser depends on before counting the fetch as data |
target-http-403 or -429 with no X-Node4-Conn-Limit header | resp.StatusCode | The target itself refused or throttled the exit | Honor Retry-After and reduce the rate; the credential is fine. See why an IP gets blocked |
A BackgroundService worker
Once one request passes every check, run many. The worker below is a hosted service (Microsoft.Extensions.Hosting and Microsoft.Extensions.Http, both 8.0.1 in the run) that drains a queue with bounded concurrency. What the proxy adds to an ordinary queue worker: one session id per attempt, so all of an attempt's requests share an exit, and one handler per session, because of the pool-key rule above. A retry salts the id, which opens a new session and therefore a new exit pick (possibly the same address again, which is not a fault). A credential refusal stops the host, since no job can succeed with the credential every job shares; a ceiling refusal, a session that cannot be pinned, or a timeout earns a bounded, backed-off retry. IHttpClientFactory supplies the one client that is not per-session, the direct one.
using System.Net;
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
// Environment: NODE4_PROXY_URL http://gw-rotating_datacenter.node4.io:8083 or socks5://...:1083 (unset = direct)
// NODE4_PROXY_USER, NODE4_PROXY_PASS
// TARGET_URL (default https://node4.io/api/tools/ip), WORKERS (default 4)
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton(ProxySettings.FromEnvironment());
builder.Services.AddSingleton<SessionClients>();
builder.Services.AddHostedService<FetchWorker>();
// One named client per proxy PRODUCT, configured once. The handler owns the connection pool,
// so handler rotation at the factory level is switched off and PooledConnectionLifetime does
// the DNS refresh instead (the combination Microsoft documents for SocketsHttpHandler + factory).
builder.Services.AddHttpClient("direct")
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
UseProxy = false,
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
})
.SetHandlerLifetime(Timeout.InfiniteTimeSpan);
using IHost host = builder.Build();
await host.RunAsync();
return Environment.ExitCode;
sealed record ProxySettings(Uri? ProxyUri, string User, string Password, Uri Target, int Workers)
{
public static ProxySettings FromEnvironment()
{
string? url = Environment.GetEnvironmentVariable("NODE4_PROXY_URL");
return new ProxySettings(
string.IsNullOrEmpty(url) ? null : new Uri(url),
Environment.GetEnvironmentVariable("NODE4_PROXY_USER") ?? "",
Environment.GetEnvironmentVariable("NODE4_PROXY_PASS") ?? "",
new Uri(Environment.GetEnvironmentVariable("TARGET_URL") ?? "https://node4.io/api/tools/ip"),
int.TryParse(Environment.GetEnvironmentVariable("WORKERS"), out int w) ? w : 4);
}
/// Targeting rides in the username. Order: base, -country-xx, -session-ID.
public string Username(string? country, string? session)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(User, "^[A-Za-z0-9_-]+$") || System.Text.RegularExpressions.Regex.IsMatch(User, "-(session|country|city|state|asn)-"))
throw new ArgumentException("proxy username: letters, digits, underscores and hyphens only, with no targeting segment inside it");
if (session is not null && !System.Text.RegularExpressions.Regex.IsMatch(session, "^[A-Za-z0-9]{1,32}$"))
throw new ArgumentException("session id: 1 to 32 letters and digits");
return User + (country is null ? "" : "-country-" + country) + (session is null ? "" : "-session-" + session);
}
}
/// One HttpClient (and one SocketsHttpHandler, so one connection pool) per sticky session.
/// The pool key does not include the proxy credential, so a session cannot share a handler
/// with another session: the second session would ride the first session's open tunnel.
sealed class SessionClients(ProxySettings settings) : IDisposable
{
private readonly Dictionary<string, HttpClient> _clients = new();
private readonly object _lock = new();
public HttpClient For(string session)
{
lock (_lock)
{
if (_clients.TryGetValue(session, out var c)) return c;
var proxy = new WebProxy(settings.ProxyUri!)
{
BypassProxyOnLocal = false,
Credentials = new NetworkCredential(settings.Username(null, session), settings.Password),
};
var handler = new SocketsHttpHandler
{
Proxy = proxy,
UseProxy = true,
AllowAutoRedirect = false,
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
};
c = new HttpClient(handler, disposeHandler: true) { Timeout = TimeSpan.FromSeconds(30) };
_clients[session] = c;
return c;
}
}
/// Drop a session's client once the job is done (or the session must change on retry).
public void Release(string session)
{
lock (_lock)
{
if (_clients.Remove(session, out var c)) c.Dispose();
}
}
public void Dispose()
{
lock (_lock) { foreach (var c in _clients.Values) c.Dispose(); _clients.Clear(); }
}
}
sealed record Job(string Id, Uri Url, int Attempt = 1);
sealed class FetchWorker(
ProxySettings settings,
SessionClients sessions,
IHttpClientFactory factory,
IHostApplicationLifetime lifetime,
ILogger<FetchWorker> log) : BackgroundService
{
private static readonly HashSet<string> StopOn = ["proxy-auth"];
private static readonly HashSet<string> RetryOn = ["proxy-refused-429", "proxy-refused-503", "socks5-refused", "timeout", "proxy-unreachable"];
private const int MaxAttempts = 3;
protected override async Task ExecuteAsync(CancellationToken stopping)
{
var queue = Channel.CreateUnbounded<Job>();
foreach (var id in new[] { "a", "b", "c", "d", "e", "f" })
queue.Writer.TryWrite(new Job("job" + id, settings.Target));
int pending = 6, failed = 0;
string? stop = null;
using var gate = new SemaphoreSlim(settings.Workers);
var inFlight = new List<Task>();
while (stop is null && Volatile.Read(ref pending) > 0 && !stopping.IsCancellationRequested)
{
if (!await queue.Reader.WaitToReadAsync(stopping)) break;
if (!queue.Reader.TryRead(out var job)) continue;
await gate.WaitAsync(stopping);
inFlight.Add(Task.Run(async () =>
{
try
{
var r = await FetchAsync(job, stopping);
if (StopOn.Contains(r.Cause))
{
stop = r.Cause;
log.LogError("{Job} attempt={Attempt} {Cause}: the proxy refused the credential, stopping the queue", job.Id, job.Attempt, r.Cause);
queue.Writer.TryComplete();
return;
}
if (RetryOn.Contains(r.Cause) && job.Attempt < MaxAttempts)
{
var delay = TimeSpan.FromSeconds(Math.Min(30, Math.Pow(2, job.Attempt))) + TimeSpan.FromMilliseconds(Random.Shared.Next(1000));
log.LogWarning("{Job} attempt={Attempt} {Cause}: retry in {Delay:F1}s with a new session", job.Id, job.Attempt, r.Cause, delay.TotalSeconds);
await Task.Delay(delay, stopping);
queue.Writer.TryWrite(job with { Attempt = job.Attempt + 1 });
return;
}
if (r.Cause != "ok") Interlocked.Increment(ref failed);
log.LogInformation("{Job} attempt={Attempt} {Cause} exit={Exit} detail={Detail}", job.Id, job.Attempt, r.Cause, r.Exit ?? "-", r.Detail);
Interlocked.Decrement(ref pending);
if (Volatile.Read(ref pending) == 0) queue.Writer.TryComplete();
}
finally { gate.Release(); }
}, stopping));
inFlight.RemoveAll(t => t.IsCompleted);
}
await Task.WhenAll(inFlight);
if (stop is not null) { log.LogError("stopped: {Cause}; fix the credential, then rerun", stop); Environment.ExitCode = 1; }
else if (failed > 0) { log.LogError("{Failed} job(s) failed after retries", failed); Environment.ExitCode = 2; }
lifetime.StopApplication();
}
private async Task<FetchResult> FetchAsync(Job job, CancellationToken ct)
{
// one session id per attempt: a retry salts it, which starts a new session (a new exit pick)
string session = job.Attempt > 1 ? $"{job.Id}a{job.Attempt}" : job.Id;
HttpClient client = settings.ProxyUri is null ? factory.CreateClient("direct") : sessions.For(session);
try
{
using var resp = await client.GetAsync(job.Url, ct);
string body = await resp.Content.ReadAsStringAsync(ct);
return Classify(resp, body);
}
catch (Exception ex) { return Classify(ex); }
finally { if (settings.ProxyUri is not null) sessions.Release(session); }
}
/// The gateway's answer and the target's answer are kept apart: a 407 is only ever the proxy's;
/// a 502 on a plain-HTTP target is the gateway's only with one of the gateway's bodies.
static FetchResult Classify(HttpResponseMessage resp, string body)
{
int status = (int)resp.StatusCode;
bool conn = resp.Headers.Contains("X-Node4-Conn-Limit");
bool sticky503 = resp.Headers.TryGetValues("X-Node4-Sticky", out var v) && v.Contains("unavailable");
bool gatewayBody = body.StartsWith("no exit available") || body.StartsWith("upstream error");
string cause = status switch
{
407 => "proxy-auth",
429 when conn => "proxy-refused-429",
503 when sticky503 => "proxy-refused-503",
502 when gatewayBody => "proxy-refused-502",
>= 200 and < 300 => "ok",
_ => "target-http-" + status,
};
string? exit = null;
if (cause == "ok") { try { exit = JsonDocument.Parse(body).RootElement.GetProperty("ip").GetString(); } catch (JsonException) { } }
return new FetchResult(cause, exit, body.Length > 60 ? body[..60] : body);
}
static FetchResult Classify(Exception ex) => ex switch
{
// HTTPS target: the gateway refused the CONNECT, so there is no response object; the status is in the message
// (and in StatusCode from .NET 9 on). 407 credential, 502 country or no exit reached the target,
// 503 session, 429 connection ceiling.
HttpRequestException { HttpRequestError: HttpRequestError.ProxyTunnelError } h when h.InnerException is null
=> TunnelStatus(h.Message) switch { 407 => new("proxy-auth", null, h.Message), int s => new("proxy-refused-" + s, null, h.Message) },
// SOCKS5: the gateway accepts the credential exchange and refuses the connect with reply 2 for every
// 407 cause and for the connection ceiling alike; .NET 10 appends the reply byte to the message.
HttpRequestException { HttpRequestError: HttpRequestError.ProxyTunnelError } h => new("socks5-refused", null, h.InnerException!.Message),
HttpRequestException { HttpRequestError: HttpRequestError.NameResolutionError or HttpRequestError.ConnectionError } h => new("proxy-unreachable", null, h.Message),
HttpRequestException { HttpRequestError: HttpRequestError.SecureConnectionError } h => new("tls", null, h.Message),
TaskCanceledException { InnerException: TimeoutException } t => new("timeout", null, t.InnerException!.Message),
TaskCanceledException => new("canceled", null, ex.Message),
HttpRequestException h => new("http-" + h.HttpRequestError, null, h.Message),
_ => new("error-" + ex.GetType().Name, null, ex.Message),
};
static int TunnelStatus(string message)
{
var m = System.Text.RegularExpressions.Regex.Match(message, @"status code '(\d{3})'");
return m.Success ? int.Parse(m.Groups[1].Value) : 0;
}
}
sealed record FetchResult(string Cause, string? Exit, string Detail);Expected result: six info lines, ok with an exit address for each job, and process exit code 0; with NODE4_PROXY_URL unset every line shows your own address through the direct named client, which is the comparison. With a credential refused over the HTTP port, the run against the gateway printed four fail lines (the four jobs in flight), each attempt=1 proxy-auth: the proxy refused the credential, stopping the queue, then stopped: proxy-auth; fix the credential, then rerun, and exited 1, so a scheduler sees a failed process rather than a queue that emptied into error lines. On the SOCKS5 port the refusal is reply 2, indistinguishable from the ceiling, so the worker printed socks5-refused: retry in 2.9s with a new session for each job, retried each twice with backoff, reported 6 job(s) failed after retries and exited 2.
Two details that matter in production. sessions.Release disposes the session's client in finally, which closes its tunnel; without it, each finished job would leave an idle tunnel open until PooledConnectionIdleTimeout, and on Rotating Unmetered, which is priced by concurrent connections, idle tunnels count against the ceiling you bought, from this worker and from any other process on the same plan (connection limits). And WORKERS bounds in-flight jobs, so it also bounds live handlers. A job whose cookies or location must survive a retry should reuse its original session id rather than salt it, and cope with the session window ending.
Where this is the wrong tool
- The content is rendered by scripts.
HttpClientreturns the server's bytes and runs nothing. For a page that only exists after the browser has run, drive a browser instead; Puppeteer and Playwright through a proxy shows where the proxy credential goes there. - One address has to stay yours for weeks. Sessions on a rotating gateway last minutes, not weeks. A dedicated datacenter proxy is a fixed address held for the life of the plan with no data cap; its host and port go into
WebProxyas they are, with a plain username. - Your target scores datacenter ranges down. Serious anti-bot systems do, and nothing on
SocketsHttpHandlerchanges what network the exit sits in. Point the same program at the residential gateway (host and port in the table above) and read its stricter username grammar first. - You need UDP over SOCKS5.
HttpClientis TCP only, as are the gateways.UDP ASSOCIATEexists on request for US shared and dedicated datacenter IPs (SOCKS5 support), and reaching it takes a raw socket, notHttpClient. - You have no paid plan yet. Gateway and SOCKS5 tests need one; the rotating proxies page describes the two rotating plans. Until then the free tier's static shared proxies take
Proxy.Clientoverhttp://, which settles whether your credential handling is right.
A credential inside the WebProxy address, the second row of the credential table above, is what curl -U user:pass -x host:port becomes when it is translated by hand. The proxy connection builder assembles the full connection string plus curl, Python, Node.js and Scrapy snippets from a protocol, host, port and credential, so you can check the host, port and username your C# should carry; then put the credential in NetworkCredential, not the URL.
FAQ
How do I use a proxy with HttpClient in C#?
Create a WebProxy with http://HOST:PORT, set its Credentials to a NetworkCredential, assign it to SocketsHttpHandler.Proxy with UseProxy = true, and pass the handler to new HttpClient(handler). Reuse that client; do not create one per request.
Why does HttpClient throw "The proxy tunnel request to proxy ... failed with status code '407'"?
While the HTTPS tunnel was being opened the proxy rejected the credential, so no response object exists; the exception is HttpRequestException with HttpRequestError.ProxyTunnelError, and StatusCode is null on .NET 8 and 407 on .NET 9 and later. Check first for a credential placed in the WebProxy address, which .NET does not read; it belongs in Credentials.
Does HttpClient support SOCKS5 proxies?
Yes, on .NET 6 and later through SocketsHttpHandler (and HttpClientHandler, which wraps it): new WebProxy("socks5://host:port") { Credentials = ... }. Username and password authentication is included, the target hostname is resolved by the proxy, and socks5h:// is not an accepted scheme.
Should I percent-encode the proxy password in C#?
No. NetworkCredential sends the username and password exactly as given. Percent-encoding is for a credential inside a URL, which in .NET only the proxy environment variables (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY) read; a WebProxy address ignores it.
How do I tell a timeout from a cancellation?
Both throw TaskCanceledException. A timeout, whether HttpClient.Timeout or SocketsHttpHandler.ConnectTimeout, carries a TimeoutException as InnerException; your own token's cancellation does not.
How do I get a different IP on each connection in C#?
An exit is picked when a connection to an exit opens: each CONNECT tunnel, each SOCKS5 connection, and each plain http:// request on the HTTP port, which the gateway forwards over its own connection. So for HTTPS targets make every request open its own tunnel: set request.Headers.ConnectionClose = true, or give the handler a short PooledConnectionIdleTimeout. Each new tunnel is a new pick, so the same address can come back, and each costs a 407 round trip. To hold one exit on purpose, add -session-<id> to the username and give that session its own handler.
HttpClientHandler or SocketsHttpHandler for a proxy?
Both work, and on .NET Core and .NET 5 or later they are the same code: HttpClientHandler wraps SocketsHttpHandler, so proxy, SOCKS5 and the exceptions behave identically. SocketsHttpHandler adds ConnectTimeout, PooledConnectionLifetime and PooledConnectionIdleTimeout, which this page relies on, so prefer it in new code.
Does IHttpClientFactory work with a proxy?
Yes: configure the proxy on the primary handler of a named client with ConfigurePrimaryHttpMessageHandler, one name per proxy. Keep the set of names bounded, and either accept the two-minute handler lifetime or set it to infinite and let PooledConnectionLifetime refresh DNS.
Related guides
- Authenticating curl through a proxy: reproduce any refusal on this page with one command before touching C#
- curl SOCKS5 vs HTTP proxy workflow, where
socks5h://is the right spelling and the resolution choice is explained - PHP cURL proxy authentication, Go net/http proxy authentication and Java HttpClient proxy authentication: three more standard clients, each with its own way of surfacing a refused
CONNECT - Node.js production-ready proxy rotation, a comparable queue worker built on Node agents
- SOCKS5 proxy setup: SOCKS5 ports per product, with curl, Python and Node examples