Loading KAIROXO page正在加载 KAIROXO 页面Đang tải trang KAIROXO

KAIROXO
Tutorial

HttpClient Proxy in .NET 8: Setup and Connection Reuse

Configure a proxy in .NET 8, separate proxy credentials from application authentication, reuse connections and validate the route before scaling.

KAIROXO

A laptop with a code editor and eyeglasses on a wooden desk.

An HttpClient proxy integration has two jobs: send traffic through the intended gateway and preserve predictable application behavior when that gateway is slow or unavailable. Getting a successful response once proves very little about connection reuse, cancellation or the identity of the final exit. For a .NET 8 worker, start with one explicitly configured client, one harmless diagnostic endpoint and a modest request budget.

This workflow applies to development and authorized public-data collection. It does not modify application login or grant access to a target. KAIROXO provides several network products; choose the product and copy its actual protocol, hostname, port and authentication values before translating them into C# configuration.

Define the access profile

Keep four facts together in a configuration record: the proxy transport, the task's required region, the lifetime of the network identity and the worker's concurrency budget. A fixed endpoint is useful when repeatability matters, while a rotating service changes the interpretation of an exit check. Record the intended behavior before treating different observed IP addresses as a fault.

Store credentials in your established local secret mechanism and expose them to the sample as environment variables. Do not put them in a URL that may be copied into logs. Proxy authentication belongs to WebProxy.Credentials; an Authorization header sent to the destination serves a different purpose and should not contain the proxy password.

Implementation steps

  1. Configure an explicit handler

    Create the handler before the first request and configure its proxy once. The example uses SocketsHttpHandler because connection behavior is part of the access profile. The URI contains the actual gateway scheme, host and port, while the username and password remain separate. Confirm that the chosen product supports that scheme; an HTTPS destination does not by itself mean the gateway URI starts with HTTPS.

    The pool lifetime and connection limits below are illustrative starting points, not KAIROXO service guarantees. Keep normal TLS certificate validation enabled. A certificate error needs investigation of the endpoint, trust chain and environment, rather than an accept-all certificate callback.

    Codecsharp
    using System.Net;using System.Text.Json;static string Required(string name) =>    Environment.GetEnvironmentVariable(name) is { Length: > 0 } value        ? value : throw new InvalidOperationException("Missing " + name);var endpoint = new Uri(Required("PROXY_URI"));if (!string.IsNullOrEmpty(endpoint.UserInfo))    throw new InvalidOperationException("Keep credentials out of PROXY_URI");using var handler = new SocketsHttpHandler{    Proxy = new WebProxy(endpoint) { Credentials = new NetworkCredential(        Required("PROXY_USERNAME"), Required("PROXY_PASSWORD")) },    UseProxy = true,    ConnectTimeout = TimeSpan.FromSeconds(10),    PooledConnectionLifetime = TimeSpan.FromMinutes(5),    MaxConnectionsPerServer = 4,    AllowAutoRedirect = false};using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(20));using var response = await client.GetAsync("https://httpbin.org/ip", deadline.Token);response.EnsureSuccessStatusCode();var payload = await response.Content.ReadAsStringAsync(deadline.Token);using var diagnostic = JsonDocument.Parse(payload);if (!diagnostic.RootElement.TryGetProperty("origin", out _))    throw new InvalidOperationException("Unexpected diagnostic response");// Inspect the exit locally; never log response bodies or proxy credentials.Console.WriteLine("Diagnostic succeeded; inspect the exit before scaling.");
  2. Reuse the client deliberately

    For a continuously running worker, retain a long-lived client and its handler instead of recreating them for every URL. Disposing a response and disposing the whole connection pool are different decisions. Consume or dispose each response promptly so subsequent work can use available connections. Set a finite pooled-connection lifetime when your environment needs periodic DNS refresh.

    In a hosted application, an appropriately configured IHttpClientFactory is another supported lifetime strategy. Keep configuration ownership clear: factory-managed handlers can outlive an individual client. If a task switches credentials, proxy routing or isolation requirements, use a deliberately separate handler profile rather than mutating a handler that has already sent traffic.

  3. Verify the network path

    Run the diagnostic from the same container, worker account or machine as the future job. Examine the returned origin locally and compare it with the expected network behavior. For a fixed endpoint, check repeatability; for a rotating profile, assess region and session rules instead of demanding a single permanent address. A JSON response with the expected field is only a shape check, not proof of a particular country.

    Repeat a small number of requests, then test one authorized target with the same client. Keep the endpoint, time and route profile in the test record, but exclude credentials and response bodies from centralized logging. A direct request from your laptop is not a substitute for checking the deployed worker's outbound path.

  4. Bound deadlines and retries

    ConnectTimeout limits connection establishment, while the cancellation token bounds the end-to-end diagnostic operation. HttpClient.Timeout supplies another outer limit; the earlier cancellation wins. Carry cancellation through reading and parsing instead of assuming that receiving response headers finishes the job. For large downloads, use streaming and an explicit content-size policy suited to the task.

    Retry only operations that are safe to repeat, with a finite attempt budget and a delay. An authentication failure requires configuration review; repeated password attempts are not recovery. A destination's rate limit requires slowing or pausing that destination's workload. Retrying every failure immediately can exhaust sockets, spend traffic allowance and conceal the original problem.

Measure the worker, not a single request

Track elapsed time, sanitized outcome categories, request counts and usable-result counts by access profile. Separate proxy connection failures from destination HTTP responses and parsing failures. Compare warm and cold requests, since connection establishment can dominate the first request while later requests reuse a pool.

Use a short pilot with the same URL distribution and expected response sizes as the real job. Increase concurrency only after latency and error patterns are stable. MaxConnectionsPerServer is a connection-pool control, not a complete business-level rate limiter, especially when multiple hosts and multiplexed protocols are involved. Keep a separate scheduling limit for the overall worker.

Questions before rollout

Sources and further reading

Related KAIROXO guide

Loading KAIROXO page正在加载 KAIROXO 页面Đang tải trang KAIROXO