When a C# proxy request behaves inconsistently, I first fix the proxy configuration and destination, then issue a few requests through the same HttpClient. Recreating the client after every failure can mix connection-establishment changes into the diagnosis.
This .NET 8 console example uses SocketsHttpHandler and WebProxy without extra NuGet packages. It reads the same authorized JSON endpoint three times, recording duration and array length. Three observations help inspect a configuration; they do not establish a service benchmark.
Authenticate to the correct service
Put proxy credentials in WebProxy.Credentials, not in DefaultRequestHeaders.Authorization, which is part of the destination request. Proxy authentication and destination login can coexist, but must be configured and diagnosed separately.
PROXY_URL is an HTTP proxy endpoint without embedded credentials. DATA_URL is the business endpoint. Before running, confirm that the deployment environment can reach the proxy port. With allowlist authentication, verify the caller source address required by the product, not the proxy exit observed by a destination.
Observe three requests with fixed inputs
The endpoint must return JSON containing an items array. The program reuses one client, pauses for one second between rounds, and stops on error. That pause is an example interval, not a destination request allowance; slow it down if the applicable policy requires it.
Target .NET8 with implicit usings and nullable reference types enabled. Create a console project and replace Program.cs with the complete code below. Run it after setting the required process configuration.
dotnet new console --framework net8.0 -n ProxyDemo
cd ProxyDemo
dotnet run
Set PROXY_URL, PROXY_USER, PROXY_PASS, and DATA_URL. The exit-check version also needs CHECK_URL. Use http://HOST:PORT for the credential-free proxy endpoint and inject credentials separately. Each example is an independent console project; do not paste several top-level programs into the same file.
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Diagnostics;
using System.Globalization;
try
{
using var client = ProxyTools.Create("PROXY");
var url = ProxyTools.Env("DATA_URL");
for (int round = 1; round <= 3; round++)
{
var timer = Stopwatch.StartNew();
var data = await ProxyTools.Fetch(client, url);
if (!data.TryGetProperty("items", out var items) || items.ValueKind != JsonValueKind.Array)
throw new InvalidDataException("Expected an items array");
timer.Stop();
Console.WriteLine($"round={round}, records={items.GetArrayLength()}, elapsed_ms={timer.ElapsedMilliseconds}");
if (round < 3) await Task.Delay(1000);
}
}
catch (HttpRequestException ex)
{
Console.Error.WriteLine($"Request failed; HTTP={ex.StatusCode?.ToString() ?? "unavailable"}");
Environment.ExitCode = 1;
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("Request cancelled or timed out");
Environment.ExitCode = 1;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Stopped:{ex.GetType().Name}; check configuration, JSON and fields.");
Environment.ExitCode = 1;
}
static class ProxyTools
{
public static string Env(string key) => Environment.GetEnvironmentVariable(key)
?? throw new InvalidOperationException("Missing setting: " + key);
public static HttpClient Create(string prefix)
{
var address = new Uri(Env(prefix + "_URL"));
if (address.Scheme != "http" || address.UserInfo.Length != 0)
throw new InvalidOperationException("Expected an HTTP proxy endpoint without embedded credentials");
var proxy = new WebProxy(address)
{
BypassProxyOnLocal = false,
Credentials = new NetworkCredential(Env(prefix + "_USER"), Env(prefix + "_PASS"))
};
var handler = new SocketsHttpHandler
{
Proxy = proxy, UseProxy = true, UseCookies = false,
AllowAutoRedirect = false,
ConnectTimeout = TimeSpan.FromSeconds(5),
PooledConnectionLifetime = TimeSpan.FromMinutes(2),
MaxConnectionsPerServer = 4
};
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(20),
MaxResponseContentBufferSize = 1024 * 1024 };
}
public static async Task<JsonElement> Fetch(HttpClient client, string url)
{
using var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
throw new HttpRequestException("Unexpected HTTP status", null, response.StatusCode);
if (response.Content.Headers.ContentType?.MediaType != "application/json")
throw new InvalidDataException("Expected application/json");
var bytes = await response.Content.ReadAsByteArrayAsync();
using var document = JsonDocument.Parse(bytes);
return document.RootElement.Clone();
}
}
Interpret elapsed time carefully
elapsed_ms starts before the call and ends after the response is read and its JSON structure checked. It includes networking and local work, not just proxy latency. The first request may establish a connection; later requests can also reconnect. A faster second response does not prove a provider performance improvement.
To compare candidates, keep execution region, destination, payload size, concurrency, observation window and client version consistent, and record failures as well as successes. This small loop is for understanding one environment, not producing a general ranking.
Connection lifetime is not proxy lifetime
HttpClient resolves DNS when establishing a connection. PooledConnectionLifetime limits how long a pooled connection can be reused so a later connection can resolve DNS again. It is not automatic synchronization with DNS TTL, and it is not a short-lived proxy lease.
Two minutes is an example setting. Multiple proxies can use a bounded set of separately configured clients, with limits and retirement rules for that set. Do not create an unlimited permanent client cache or recreate a full client for every product request.
Follow the error to its layer
First determine whether an HTTP status was available. Without one, inspect the endpoint, network, TLS and timeouts. For authentication evidence, verify the authentication method and account. For403 or429, check destination access and rate rules. A successful status with invalid JSON points toward response content.
The client timeout in this example applies to the default buffered GetAsync call. If the application switches to streaming, propagate a deadline to body reads as well. A five-second connection timeout and a twenty-second call timeout govern different boundaries; they are not an unconditional twenty-five-second promise.
Keep the runtime version, time, error type, status and redacted setting names in the reproduction record. Stable inputs make it possible to tell whether the next change fixed the same problem.
Frequently asked questions
Is IHttpClientFactory mandatory?
No. A bounded set of long-lived clients with appropriate connection lifetime settings is also a valid approach. Consider a factory when dependency injection and multiple managed configurations fit the application.
Does MaxConnectionsPerServer=4 mean four requests per second?
No. Connection limits are not a global request-rate limiter. HTTP version and task scheduling also affect behavior.
How is407 different from401?
407 requests proxy authentication;401 concerns the destination service. Identify the responding layer before changing either account.
Related reading
Sources
- learn.microsoft.com — technical documentation
- learn.microsoft.com — technical documentation
- learn.microsoft.com — technical documentation
About the author
林简 — Proxy integration and troubleshooting author
Expertise: Proxy fundamentals; HTTP, HTTPS and SOCKS5; password and allowlist authentication; Python and Requests integration; Scrapy and browser configuration; connection and authentication troubleshooting