C# HttpClient Proxy: How to Use Rotating Proxies with WebProxy
To use a rotating proxy in C#, you configure the HttpClient's proxy settings with a WebProxy object that includes the gateway host, port, and credentials. Targeting options and session control are passed through the proxy username string, following a specific underscore-separated grammar.
- Use the WebProxy class in System.Net to set the proxy server and port.
- Authentication and targeting are combined in the proxy username string.
- For SOCKS5 support, use a third-party library like SocksSharp.
- Always verify the exit IP to confirm your targeting and rotation work.
C# HttpClient Proxy: Where the Settings Live
The proxy configuration for an HttpClient is set via the HttpClientHandler's Proxy property, which accepts an IWebProxy object. The standard System.Net.WebProxy class implements this interface and is the primary tool for setting up an HTTP or HTTPS proxy with authentication. You create the handler, assign the WebProxy, and then pass the handler to the HttpClient's constructor. This gives you full control over the proxy for all requests made by that specific HttpClient instance.
Setting Up HTTP and HTTPS Proxy on Port 7070
To route traffic through the HTTP gateway on port 7070, instantiate a WebProxy with the gateway host and port, then set the Credentials property with a NetworkCredential containing your proxy username and password. The username must include your proxy user login and any targeting or session options. Here is a complete example for a console application:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
// Gateway host and port
var proxyUri = new Uri("http://gw.rotatingproxy.cc:7070/");
// Proxy username with login and options, password from dashboard
string proxyLogin = "USERNAME"; // Your proxy user's login
string options = "net.res_cc.us_st.ca_city.los-angeles"; // Example targeting
string fullUsername = $"{proxyLogin}_{options}";
string password = "PASSWORD";
// Create the proxy object
var proxy = new WebProxy(proxyUri)
{
Credentials = new NetworkCredential(fullUsername, password)
};
// Create the handler and HttpClient
var handler = new HttpClientHandler { Proxy = proxy };
using var client = new HttpClient(handler);
// Make a request to verify the IP
try
{
var response = await client.GetStringAsync("https://api.ipify.org");
Console.WriteLine($"Exit IP: {response}");
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Request failed: {ex.Message}");
}
}
}
This code creates an HttpClient that routes all its HTTP and HTTPS traffic through the rotating proxy gateway. The CONNECT method is used automatically for HTTPS requests. For tasks like web scraping or price monitoring, this setup is the foundation.
Using SOCKS5 Proxy on Port 7071 in C#
The standard WebProxy class in .NET does not natively support the SOCKS5 protocol. If your tool or library requires SOCKS5, you will need to use a third-party library. One reliable option is the SocksSharp library available via NuGet. After installing the SocksSharp package, you can create a SOCKS5 proxy handler. Here is how to set it up for port 7071:
// Install-Package SocksSharp
using SocksSharp;
using SocksSharp.Proxy;
// ...
var proxySettings = new ProxySettings()
{
Host = "gw.rotatingproxy.cc",
Port = 7071, // SOCKS5 port
Credentials = new NetworkCredential("USERNAME_net.mob_cc.de", "PASSWORD")
};
var handler = new ProxyClientHandler<Socks5>(proxySettings);
using var client = new HttpClient(handler);
var response = await client.GetStringAsync("https://ipinfo.io/json");
Console.WriteLine(response);
Always check the current docs for SocksSharp or any alternative library, as APIs can change. The SOCKS5 protocol can be beneficial for certain TCP-based connections beyond HTTP.
Passing Targeting and Session Options in the Username
All geo-targeting and session control is done by appending options to the proxy user's login in the username field, separated by underscores. The network is specified with net.res (residential), net.mob (mobile), net.dc (datacenter), or net.isp (ISP). Country targeting uses the lowercase ISO code like cc.us. For US states, add st.ca (for California). City targeting uses tokens like city.chicago (spaces become hyphens). To maintain a sticky session, include a session ID with sid.abc123 and an optional time-to-live like ttl.30 (minutes).
- Rotating IP (new IP each connection):
USERNAME_net.res_cc.fr - Sticky session for 20 minutes in Berlin mobile IPs:
USERNAME_net.mob_cc.de_city.berlin_sid.k3m9q2_ttl.20 - US California datacenter IPs:
USERNAME_net.dc_cc.us_st.ca
You can build these strings manually or use the proxy URL builder tool in the dashboard. For a deep dive, see the guide on sticky vs rotating sessions.
Verifying the Exit IP and Location
After configuring the proxy, your first step should be to verify the exit IP and its apparent geolocation. This confirms your targeting options are working and that traffic is flowing correctly. Use a simple IP echo service or a more detailed geolocation API within your C# code. The following example checks both and parses the JSON response from ipinfo.io:
using System.Text.Json;
// ... after creating the proxied HttpClient ...
var ipResponse = await client.GetStringAsync("https://api.ipify.org");
Console.WriteLine($"Exit IP: {ipResponse}");
var geoResponse = await client.GetStringAsync("https://ipinfo.io/json");
using var doc = JsonDocument.Parse(geoResponse);
Console.WriteLine($"Country: {doc.RootElement.GetProperty("country").GetString()}");
Console.WriteLine($"City: {doc.RootElement.GetProperty("city").GetString()}");
If the country or city does not match your targeting, double-check the username string format and ensure the targeted location is available for your chosen network. Refer to the IP check tools guide for more services.
Fixing Common Proxy Errors: 407, Timeouts, TLS
You will encounter specific HTTP errors when using proxies. A 407 status code means proxy authentication failed. This almost always indicates an incorrect username or password. Verify the full username string, ensuring the proxy user login is correct, the password matches the one in the dashboard, and the user is not paused or over its monthly GB cap. Also, ensure the user is allowed on the network specified in the net. option.
Timeouts can occur due to network latency, a slow target site, or the proxy gateway needing to find an available IP in your chosen location. Implement a retry strategy with exponential backoff and consider increasing the HttpClient's timeout properties:
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(60) };
TLS/SSL errors may surface if the target site uses stricter TLS requirements. The proxy itself does not interfere with TLS, but the exit IP's reputation might trigger challenges. Ensure your HttpClient uses a modern TLS version. You can configure this in the handler:
var handler = new HttpClientHandler
{
Proxy = proxy,
SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13,
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true // Use with caution for debugging only
};
For a systematic approach to failures, read our guide on retry strategies for proxy requests.
Tips for Running C# HttpClient Proxy at Scale
When making many concurrent requests, manage your HttpClient instances carefully. Avoid the anti-pattern of creating and disposing a new HttpClient for each request, as this can exhaust sockets. Instead, reuse a single instance or use IHttpClientFactory for dependency injection, which manages pooling and lifetimes. Be mindful of the concurrency limit of 1,000 connections per account.
To distribute traffic across different locations or sessions, create multiple HttpClient instances, each with its own WebProxy configuration using different usernames. For example, use different session IDs for separate tasks. Here's a pattern for a simple pool:
var clientPool = new List<HttpClient>();
var sessionRoot = "USERNAME_net.res_cc.us_sid.";
for (int i = 0; i < 10; i++)
{
var sid = $"sess{i:00}";
var proxy = new WebProxy("http://gw.rotatingproxy.cc:7070/")
{
Credentials = new NetworkCredential($"{sessionRoot}{sid}", "PASSWORD")
};
var handler = new HttpClientHandler { Proxy = proxy };
clientPool.Add(new HttpClient(handler));
}
// Rotate through clients in your requests
Monitor your traffic usage closely, as costs are pay-as-you-go. Implement caching and compression to reduce bandwidth, especially for large-scale operations like SERP data collection or market research.
Using the API to Manage Proxy Users and Balance
For automation, you can use the RotatingProxy REST API to check your balance, create new proxy users, or fetch usage data. This is useful for dynamic systems that need to adjust proxy configurations on the fly. First, create an API key in the dashboard. Then, use HttpClient (potentially without a proxy) to call the API endpoints:
using var apiClient = new HttpClient();
apiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "YOUR_API_KEY");
var balanceResponse = await apiClient.GetStringAsync("https://rotatingproxy.cc/api/v1/balance");
Console.WriteLine(balanceResponse);
The API allows you to build sophisticated proxy management directly into your C# application, complementing the data gathering you do with the proxies themselves for projects like AI training data collection.
Complete Example for Web Scraping with Rotation
Here is a consolidated example that ties everything together: creating an HttpClient with a rotating residential proxy, handling errors, and parsing HTML. This pattern is suitable for building a scraper for sites like Google Shopping or Amazon.
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using HtmlAgilityPack; // Install-Package HtmlAgilityPack
class Scraper
{
static async Task Main()
{
// Proxy with rotation (no session ID)
var proxy = new WebProxy("http://gw.rotatingproxy.cc:7070/")
{
Credentials = new NetworkCredential("USERNAME_net.res_cc.us", "PASSWORD")
};
var handler = new HttpClientHandler
{
Proxy = proxy,
AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
};
using var client = new HttpClient(handler);
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
try
{
var html = await client.GetStringAsync("https://httpbin.org/html");
var doc = new HtmlDocument();
doc.LoadHtml(html);
var title = doc.DocumentNode.SelectSingleNode("//h1")?.InnerText;
Console.WriteLine($"Page title: {title}");
}
catch (HttpRequestException ex) when (ex.StatusCode == (HttpStatusCode)407)
{
Console.WriteLine("Authentication error. Check username/password.");
}
catch (TaskCanceledException)
{
Console.WriteLine("Request timed out.");
}
}
}
This example uses the HtmlAgilityPack for parsing, a common choice in C#. Remember to respect robots.txt and implement polite crawling delays, as outlined in our web scraping best practices.
Questions
Can I use the same HttpClient instance for requests with different proxy settings?
No, the proxy is set at the HttpClientHandler level when the HttpClient is created. To use different proxy configurations (like different countries or session IDs), you need to create separate HttpClient instances, each with its own handler.
How do I target a specific city like New York with a C# HttpClient?
Add the city option to your proxy username. First, check the city list in the dashboard to get the correct token (e.g., new-york). Then, construct your username like: USERNAME_net.res_cc.us_city.new-york. Use this full string in the NetworkCredential.
My code works without a proxy but throws a TimeoutException with the proxy. What should I do?
Increase the HttpClient.Timeout property. Also, implement a retry loop with a delay, as the proxy may need a moment to establish a connection through an exit node in your chosen location. Check your own network firewall and ensure you can reach gw.rotatingproxy.cc on port 7070.
Is there a way to use these proxies in a .NET Core Blazor WebAssembly application?
No, Blazor WebAssembly runs in the user's browser and cannot directly configure a system-level proxy for HTTP requests. Proxy configurations must be done in a server-side .NET context, like in a backend API, console app, or service.
How can I see which proxy network I'm being charged for in my C# application?
Traffic is charged based on the network option (<code>net.res</code>, <code>net.mob</code>, etc.) in the username used for the request. You can view detailed, network-specific usage charts in the dashboard under the Usage section to monitor costs.
Can I use these proxies with the WebClient class instead of HttpClient?
Yes, the older WebClient class also supports proxies via its WebProxy property. However, HttpClient is the modern, preferred API for .NET due to better performance and async support. The proxy setup principle with WebProxy and credentials is the same.
Start with one top-up, use any network
Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.