How to Use a Proxy With C# HttpClient (.NET 8 and Later)

HttpClient has no proxy property. The proxy lives in the handler: build a WebProxy from your host and port, attach a NetworkCredential, and pass the handler in. Never paste the full proxy string into WebProxy, since credentials in the URL are ignored and every request returns a 407. Keep one client alive, and set PooledConnectionLifetime to control how often a rotating gateway gives you a fresh IP. IHttpClientFactory handles multiple proxies, HTTPS_PROXY covers containers, and a socks5:// address covers SOCKS. Verify every setup by calling api.ipify.org.
Setting a proxy on HttpClient looks easy, until the requests start leaving from your own IP, 407 breaks the flow, or you get the same exit in a row. The thing is, HttpClient has no proxy property. Instead, you have to set it up in the handler the client wraps, which is why it's slightly more indirect in .NET than in other programming languages.
So, this tutorial covers five different ways .NET (8 and later) can accept a proxy, with every method ending in a check to verify the exit.
How to set up a proxy in C# HttpClient
We have demonstrated five methods of setting up a proxy in C# HttpClient. In essence, all cover three objects: a WebProxy with host and credentials, a handler holding that proxy, and finally an HttpClient firing up that handler. The key differentiator of the methods is the handler construction, its use, and connection longevity. At the end of every method, we hit ipify.org to check the origin IP. It helps us check if the request went through the proxy or directly.
Before starting, ensure you have:
- A supported SDK: The code runs on .NET 8 and later. However, .NET 8 and .NET 9 both reached end of support on 10 November 2026, so consider .NET 10 (LTS) for anything new.
- A console project. dotnet new console is enough.
- A proxy endpoint. Host, port, and either a username and password, or a whitelisted IP.
The first thing is to run a baseline script to get the local IP (note it down somewhere). Every other method we do compares against this.
using var client = new HttpClient();
Console.WriteLine(await client.GetStringAsync("https://api.ipify.org"));Method 1: WebProxy on HttpClientHandler in C#
This method suits simple scripts and one-off jobs. If you need anything long-running, it serves as a basis for the later methods.
using System.Net;
var host = Environment.GetEnvironmentVariable("PROXY_HOST");
var port = Environment.GetEnvironmentVariable("PROXY_PORT");
var user = Environment.GetEnvironmentVariable("PROXY_USER");
var pass = Environment.GetEnvironmentVariable("PROXY_PASS");
var handler = new HttpClientHandler
{
Proxy = new WebProxy($"http://{host}:{port}")
{
Credentials = new NetworkCredential(user, pass)
},
UseProxy = true
};
using var client = new HttpClient(handler);
var ip = await client.GetStringAsync("https://api.ipify.org");
Console.WriteLine(ip);A proxied request will obviously return the gateway's exit IP rather than the local IP address as returned with the baseline script.
WebProxy, NetworkCredential, and UseProxy = true are critical elements of this method. They pass the proxy server host URL, username/password, and tell the handler to route via the intermediary server.
Each mistake here fails in its own way. A wrong host or port throws on connect, wrong credentials come back as a 407, UseProxy = false goes direct, and a missing Proxy falls back to the system default, which is usually your own IP.
And please remember not to paste the entire proxy string from your provider in WebProxy. They are kept in the address but ignored, so every request returns 407. So pass the host and port to WebProxy, and the username and password to NetworkCredential.
Look out for:
- A 407 error means the request indeed reached the proxy but with incorrect credentials. Fix NetworkCredential or get a whitelisted IP.
- A SocketException on connect means a wrong host or port, a dead endpoint, or a blocked port. Test the same setup with curl -x before adapting.
- The SSL connection could not be established generally means an HTTP-only port used for HTTPS or a (corporate) proxy decrypting traffic. Switch to another port or trust the CA, but don't disable certificate validation to get past this. To see which certificate arrived, print it from ServerCertificateCustomValidationCallback and return errors == SslPolicyErrors.None.
- An error saying the proxy tunnel request failed with status code 501 (or 405) means the endpoint isn't a proxy at all. A normal web server has no CONNECT handler, so it rejects the method.
Note: Methods 2 to 5 reuse the four Environment.GetEnvironmentVariable lines and host, port, user, and pass from Method 1. Method 5 also plugs a fifth variable for the SOCKS5 port, which is not the same port as the HTTP one.
Method 2: SocketsHttpHandler with PooledConnectionLifetime in C#
This approach allows you to have control over how long .NET waits when a proxy doesn't answer and the connection lifetime. Both of these properties are something that HttpClientHandler can't address, as it has been a wrapper over SocketsHttpHandler since .NET Core 2.1. So, we use SocketsHttpHandler instead, which is better for a long-running service or anything beyond a simple script.
var handler = new SocketsHttpHandler
{
Proxy = new WebProxy($"http://{host}:{port}")
{
Credentials = new NetworkCredential(user, pass)
},
UseProxy = true,
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
ConnectTimeout = TimeSpan.FromSeconds(10)
};
using var client = new HttpClient(handler);Build a client on this handler and keep it for the program's lifespan, as a static field or a singleton. Do not create a new one for each request, as it may exhaust the available ports under load.
ConnectTimeout dictates how long .NET waits for the proxy connection before sending requests. Without it, the attempt gave up after 21.1 seconds against a dead gateway on Windows. With a 10-second timeout set, the attempt ended at exactly that limit. Neither came close to the 100-second HttpClient.Timeout ceiling, which covers the whole request and was never fired.
.NET pools connections, and this is governed by PooledConnectionLifetime in this method. Without it, a connection can stay open indefinitely, so a long-lived client won't notice a DNS or a gateway address change. Two minutes is a reasonable default to pick up address changes and avoid handshakes on every request.
It also decides how often you get a new exit. Byteful's residential gateway assigns a new IP for every connection, so five requests sharing one pooled connection get a single exit:
Request 1: 203.0.113.17
Request 2: 203.0.113.17
Request 3: 203.0.113.17
Request 4: 203.0.113.17
Request 5: 203.0.113.17But when you set the lifetime to TimeSpan.Zero, each request opens its own connection and gets its own exit.
Request 1: 203.0.113.42
Request 2: 203.0.113.88
Request 3: 203.0.113.5
Request 4: 203.0.113.129
Request 5: 203.0.113.61However, it also costs a new TCP connection and TLS handshake per request, which will increase latency. Therefore, use zero when explicitly necessary.
Look out for:
- SocketException if appearing only under load indicates a new HttpClient per request and exhausted sockets. Fix it by keeping one client per handler.
- Same exit IP for too long signals reused connections. Avoid it by setting PooledConnectionLifetime.
- Failures with ConnectTimeout don't return the address, port, and the reason you would get otherwise. So, log the proxy details yourself in this case.
Method 3: IHttpClientFactory named clients per proxy in ASP.NET Core
Method 3 upgrades the client to use multiple proxies at the same time, which can come in handy for extensive geo-targeting or multiple locale-based logged-in identities running side-by-side. Without it, a handler commits to its settings upfront, and changing the proxy afterward results in:
System.InvalidOperationException
This instance has already started one or more requests. Properties can only be modified before sending the first request.So, IHttpClientFactory steps in if your application needs multiple proxy exits simultaneously.
services.AddHttpClient("residential-de")
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
Proxy = new WebProxy($"http://{host}:{port}")
{
Credentials = new NetworkCredential(user, pass)
},
UseProxy = true
});The factory reuses handlers and replaces them after every two minutes by default. This helps you get multiple clients with fewer connection pools and no socket exhaustion to look after.
Please note that the proxy must be set on the primary handler, the innermost one that opens the connection, with ConfigurePrimaryHttpMessageHandler. A proxy set anywhere else in the pipeline, such as inside a handler added with AddHttpMessageHandler, never reaches the wire, so the request goes direct without any warning.
Register one named client per identity. It gives every agent, geographic target, or sticky session its own registration, so a handler is relieved of changing proxies. Then resolve IHttpClientFactory from DI and run the same check:
var client = factory.CreateClient("residential-de");
Console.WriteLine(await client.GetStringAsync("https://api.ipify.org"));At Byteful, a rotating and sticky gateway only differs in the username. Rotating is the default, and sticky appends a session and a lifetime. For instance, _s_demo1_ttl_10m when added to the username asks the gateway to hold one exit IP for ten minutes (maximum allowed is 24 hours).
Named client "rotating":
Request 1: 203.0.113.42
Request 2: 203.0.113.88
Request 3: 203.0.113.5
Named client "sticky":
Request 1: 203.0.113.17
Request 2: 203.0.113.17
Request 3: 203.0.113.17Look out for:
- A proxy that doesn't change after a configuration change means the handler is still cached. Either wait out the two-minute recycle, or change the interval with SetHandlerLifetime. If two named clients share the same proxy, check that each has their own ConfigurePrimaryHttpMessageHandler.
- Package restores failing with a connection error to an unknown address indicate a stale HTTP_PROXY or HTTPS_PROXY in the shell, which NuGet reads too. Clear them, or set them only for the specific command.
Method 4: HttpClient.DefaultProxy and environment variables in .NET
This method suits containers and CI pipelines where you don't want to configure proxies per client and set them for the whole process instead. There are two ways to do it in .NET. You can do it in code with HttpClient.DefaultProxy, or from the environment with HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and NO_PROXY.
We have primarily covered the latter since it lets you set proxies in a container and change them without a recompile. So, set it globally with this snippet:
export HTTPS_PROXY="http://user:pass@residential.byteful.com:8635"
export NO_PROXY=".internal.example.com"Now every client whose handler sets no proxy of its own picks it up:
using var client = new HttpClient();
var ip = await client.GetStringAsync("https://api.ipify.org");.NET reads those variables once, the first time a client needs the default proxy, and the result becomes HttpClient.DefaultProxy, which a client falls back to if its own handler sets no proxy. Changes after that first read are ignored.
Note that unlike the WebProxy constructor, the environment form accepts credentials in the URL. So you can use full proxy strings like http://user:pass@host:port.
Look out for:
- Local IP shows up even with the variables set. An explicit proxy in code and UseProxy = false both override the environment, so check the handler first.
- The variable is chosen by the target URL, so set both HTTP_PROXY and HTTPS_PROXY if you need to fetch both. Otherwise, some requests may leave from the real IP.
- .example.com covers subdomains, which a bare example.com does not, and wildcards like *.example.com are not supported at all.
Method 5: SOCKS5 proxies with C# HttpClient
We have used an HTTP proxy till now, but .NET also supports SOCKS. At Byteful, only the port changes when you switch protocols. Everything remains the same, except for the following changes:
Proxy = new WebProxy($"socks5://{host}:{socksPort}")
{
Credentials = new NetworkCredential(user, pass)
}Simply replace socksPort with the appropriate port number you get from your provider's dashboard.
Note: When using Byteful proxies, stick to socks5://. Using socks4:// forces .NET to resolve the domain locally on your machine and send a bare IP to the proxy, which Byteful blocks by default (and blocks outright on residential and mobile proxies).
This works on either handler since .NET 6, and includes SOCKS4, SOCKS4a, and SOCKS5. Remember, only SOCKS5 takes a password; the rest (SOCKS4 and SOCKS4a) only define a user ID.
Look out for:
- SOCKS failures return as a SocksException inside an HttpRequestException and not as a clear 407. So read the inner message to identify the real failure.
- "Failed to authenticate with the SOCKS server" means the credentials were wrong. "SOCKS server did not return a suitable authentication method" means none were sent, even if the wording suggests a server-side problem.
- Pointing socks5:// at an HTTP port, or the reverse, fails during the handshake with a protocol or version error, never an HTTP status code. Check the scheme and port pairing first.
Which proxy to use with C# HttpClient
With the .NET side settled, it comes to choosing the right proxy for the specific job at hand. This is how different proxy types work in general:
- Rotating residential: At Byteful, our residential backconnect gateways rotate IPs with a single endpoint. And for identity-sensitive workflows, Byteful offers sticky sessions with a TTL from one minute to 24 hours by just changing the username.
- Mobile proxies: Mobile IPs are best for ultra-sensitive targets by offering high anonymity since every single IP is shared by thousands of real devices through carrier-grade NAT. These also get rotation and sticky sessions similar to residential proxies.
- Static residential (ISP): For higher performance and long-living tasks that need a fixed identity. This keeps the same IP(s) for the whole subscription length and gives access to top ISPs, including Spectrum and AT&T.
- Datacenter IPs: A budget-friendly choice that offers the best performance against low-risk websites.
On top of this, we'd suggest using TCP/IP fingerprint emulation (for datacenter and ISP proxies). Targets can read the operating system from the TCP handshake, so this helps when your target's ideal device profile is Windows (as identified by your browser stack), but the underlying Linux-hosted proxy server leads to a fingerprint mismatch.
Likewise, OS targeting (for residential and mobile proxies) allows for selecting an operating system to exit the traffic from. You can choose both of these filters from Byteful's dashboard.
In addition to these, the dashboard also gives the number of live IPs per selected filter so that you know the approximate pool size available for rotation. Try these and more with a 1GB free residential trial by simply signing up.


