v1.10.82-f67ee7d
Skip to main content
← Back to Hex Proxies

C# HttpClient Proxy Integration

Use Hex Proxies in .NET with HttpClient and a proxy handler.

C# HttpClient Proxy Setup

C#'s HttpClient is the standard HTTP client for .NET applications. It supports proxy configuration through HttpClientHandler, providing clean integration with Hex Proxies for web scraping, API access, and data collection in .NET projects. The key to reliable proxy usage in .NET is proper HttpClient lifecycle management — creating a single client instance and reusing it.

Complete Configuration with Authentication

using System.Net;

var proxyUser = Environment.GetEnvironmentVariable("PROXY_USER"); var proxyPass = Environment.GetEnvironmentVariable("PROXY_PASS");

var proxy = new WebProxy("http://gate.hexproxies.com:8080", false) { Credentials = new NetworkCredential(proxyUser, proxyPass) };

var handler = new HttpClientHandler { Proxy = proxy, UseProxy = true, AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, MaxConnectionsPerServer = 20, };

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

client.DefaultRequestHeaders.UserAgent.ParseAdd( "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"); client.DefaultRequestHeaders.AcceptLanguage.ParseAdd("en-US,en;q=0.9");

var response = await client.GetAsync("https://httpbin.org/ip"); var body = await response.Content.ReadAsStringAsync(); Console.WriteLine($"[{(int)response.StatusCode}] {body}"); ```

Using IHttpClientFactory (Recommended for ASP.NET)

In ASP.NET Core applications, use IHttpClientFactory with named clients for proper lifecycle management:

// In Startup.cs or Program.cs
builder.Services.AddHttpClient("proxied", client =>
{
    client.Timeout = TimeSpan.FromSeconds(30);
    client.DefaultRequestHeaders.UserAgent.ParseAdd(
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
    var proxy = new WebProxy("http://gate.hexproxies.com:8080")
    {
        Credentials = new NetworkCredential(
            Environment.GetEnvironmentVariable("PROXY_USER"),
            Environment.GetEnvironmentVariable("PROXY_PASS"))
    };
    return new HttpClientHandler { Proxy = proxy, UseProxy = true };

// In your service class public class MyService { private readonly HttpClient _client; public MyService(IHttpClientFactory factory) { _client = factory.CreateClient("proxied"); } } ```

Geo-Targeted Requests

Modify the proxy credentials per request for geo-targeting:

var geoProxy = new WebProxy("http://gate.hexproxies.com:8080")
{
    Credentials = new NetworkCredential(
        proxyUser + "-country-de", proxyPass)
};

Common Pitfalls

The biggest .NET mistake is creating a new HttpClient per request. This causes socket exhaustion because disposed HttpClients leave sockets in TIME_WAIT state. Always reuse HttpClient instances or use IHttpClientFactory. Another issue: HttpClientHandler does not support changing the proxy after client creation. For dynamic proxy switching, create separate handler/client pairs per proxy configuration.

Retry with Polly

For production proxy usage, add Polly retry policies:

builder.Services.AddHttpClient("proxied")
    .AddTransientHttpErrorPolicy(p =>
        p.WaitAndRetryAsync(3,
            attempt => TimeSpan.FromSeconds(attempt * 2)));

This automatically retries on 5xx errors and network failures with exponential backoff.

Integration Steps

1

Create WebProxy with credentials

Initialize a WebProxy with gate.hexproxies.com:8080 and set NetworkCredential with your Hex Proxies username and password from environment variables.

2

Configure HttpClientHandler

Set UseProxy to true, attach the proxy, and configure MaxConnectionsPerServer to match your proxy plan concurrency.

3

Reuse the HttpClient instance

Create one HttpClient and reuse it across all requests to prevent socket exhaustion. In ASP.NET Core, use IHttpClientFactory for proper lifecycle management.

4

Add retry policies

Use Polly or manual retry logic to handle transient proxy failures and 403/429 responses with exponential backoff.

Operational Tips

Keep sessions stable for workflows that depend on consistent identity. For high-volume collection, rotate IPs and reduce concurrency if you see timeouts or 403 responses.

  • Prefer sticky sessions for multi-step flows (auth, checkout, forms).
  • Rotate per request for scale and broad coverage.
  • Use timeouts and retries to handle transient failures.

Frequently Asked Questions

Does HttpClient support SOCKS5?

The built-in HttpClientHandler does not support SOCKS5 directly. Use a third-party library like Shadowsocks or create a custom handler that wraps a SOCKS5 connection. For most use cases, the HTTP proxy at gate.hexproxies.com:8080 is sufficient.

Why do I get socket exhaustion errors with HttpClient?

Creating a new HttpClient per request leaves sockets in TIME_WAIT state. Always reuse HttpClient instances or use IHttpClientFactory in ASP.NET Core, which manages the handler lifecycle and connection pooling automatically.

How do I rotate IPs in C# HttpClient?

Embed a unique session ID in the proxy username (e.g., user-session-abc123). Since HttpClientHandler proxy settings are immutable after creation, create a new handler/client pair per session group or use a custom DelegatingHandler for dynamic routing.

Ready to Integrate?

Start using residential proxies with C# HttpClient today.