.NET proxy configuration
C# HttpClient Proxy: Authentication and Working Examples
Configure a C# HttpClient proxy with WebProxy, secure credentials, timeouts, cancellation, and response checks. The examples keep one client per proxy configuration and separate connection errors from HTTP responses.
Quick answer: create a WebProxy, assign it to the handler’s Proxy property, set UseProxy = true, then construct HttpClient with that handler. Read credentials from a protected configuration source, reuse the client for requests that share the same proxy, set explicit timeouts, and inspect both exceptions and HTTP status codes. See where each setting goes.
Set up a C# HttpClient proxy with WebProxy
The complete .NET 8+ console example uses SocketsHttpHandler to set a connection timeout separately from the request timeout. Create a console project, then replace its Program.cs with the example.
dotnet new console -o ProxyCheck -f net8.0
#nullable enable
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public static class ProxyCheck
{
public static async Task<int> Main(string[] args)
{
string proxyUrl = Environment.GetEnvironmentVariable("PROXY_URL")
?? throw new InvalidOperationException("Set PROXY_URL");
if (!Uri.TryCreate(proxyUrl, UriKind.Absolute, out Uri? endpoint)
|| endpoint.Scheme != "http" || endpoint.UserInfo.Length != 0)
{
throw new ArgumentException("Use an http:// proxy URL without credentials");
}
string? user = Environment.GetEnvironmentVariable("PROXY_USER");
string? password = Environment.GetEnvironmentVariable("PROXY_PASSWORD");
if ((user is null) != (password is null))
{
throw new InvalidOperationException("Supply both proxy credentials or neither");
}
var proxy = new WebProxy(endpoint);
if (user is not null && password is not null)
{
proxy.Credentials = new NetworkCredential(user, password);
}
var handler = new SocketsHttpHandler
{
UseProxy = true,
Proxy = proxy,
ConnectTimeout = TimeSpan.FromSeconds(5),
AllowAutoRedirect = false
};
using var client = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(15)
};
var target = new Uri(args.Length == 0 ? "https://api64.ipify.org" : args[0]);
try
{
using var response = await client.GetAsync(target);
Console.WriteLine($"HTTP {(int)response.StatusCode}");
if (!response.IsSuccessStatusCode)
{
return 1;
}
Console.WriteLine((await response.Content.ReadAsStringAsync()).Trim());
return 0;
}
catch (OperationCanceledException)
{
Console.Error.WriteLine("Request timed out or was canceled");
return 1;
}
catch (HttpRequestException error)
{
Console.Error.WriteLine($"Request failed: {error.HttpRequestError}");
return 1;
}
}
}
Set PROXY_URL to your HTTP proxy endpoint, for example http://proxy.example.net:8080. Inject PROXY_USER and PROXY_PASSWORD from protected configuration for an authenticated endpoint. Leave both unset when a source-IP allowlist grants access.
dotnet run --project ProxyCheck
The default destination returns the observed public IP as plain text. To use a diagnostic endpoint you control, add -- and its URL to the run command. This client disables redirects so you can see the first response.
How HttpClient chooses a proxy
- Explicit proxy. Set
UseProxy = trueand assign aWebProxytoSocketsHttpHandler.ProxyorHttpClientHandler.Proxybefore constructing the client. Review bypass rules on that proxy object for the destination URI. - Runtime default. With
UseProxy = trueandProxy = null, modern .NET usesHttpClient.DefaultProxy. Its default settings can come from the process environment or the operating system. CheckHTTP_PROXY,HTTPS_PROXY,ALL_PROXYandNO_PROXYin the process that runs the application. - Direct comparison. Set
UseProxy = falseon a separate handler and use that client to compare the same permitted URL over a direct connection.
For an explicit WebProxy, call IsBypassed with the actual destination URI to inspect the object’s bypass decision. See Microsoft’s HttpClient.DefaultProxy reference for .NET 10 for platform and environment behavior.
Set proxy credentials on WebProxy

WebProxy. If the destination API also requires a token, add it to the request’s Authorization header.WebProxy.Credentials handles proxy authentication. The destination API’s Authorization header belongs on its own request. The example takes credentials separately from the proxy URL and reports the runtime’s error category without logging the exception message or credentials. See Microsoft’s WebProxy credentials reference and our Python Requests proxy credentials.
For an IP-authorized proxy, confirm the public source IP of the machine running the program. An HTTPS destination still uses an http:// proxy URL when the connection to the proxy itself uses plain HTTP. An HTTPS CONNECT tunnel protects the traffic to the destination after the tunnel opens. Basic credentials sent to a plain HTTP proxy are outside that TLS connection.
Which property should hold the proxy credentials?
- Explicit WebProxy. Set
WebProxy.Credentialson the proxy you assign tohandler.Proxy. Keep the login with the endpoint when you create separate clients for different proxies. - Default proxy. With
UseProxy = trueandProxy = null, useHttpClientHandler.DefaultProxyCredentialsfor the default proxy. Confirm the proxy selected in the process that runs the app. - Destination authentication. Use
HttpClientHandler.Credentialsfor the origin server’s challenge or a requestAuthorizationheader for an API token. A proxy’s407needs proxy credentials.
Observed on .NET 10.0.14. In a local HTTP test, the proxy asked for Basic authentication and accepted both documented setups. This runtime also used DefaultProxyCredentials when an explicit WebProxy had no credentials. Credentials supplied on that object took precedence when both properties were set. Origin credentials alone left the request at 407. Set credentials on the object that owns the proxy connection so each client has clear behavior. Runtime source for this version
Use cancellation and classify failures
The program allows five seconds to establish a connection and fifteen seconds for the request. Timeouts can originate in DNS, the proxy connection, TLS negotiation or the destination. The default GetAsync call buffers the response. For streaming, pass a cancellation token through response-body reads as well.
HTTP forwarding can return 407 as a response. A 407 during HTTPS CONNECT can surface as HttpRequestException with HttpRequestError.ProxyTunnelError before you get a destination response. Check the proxy challenge and credentials. The proxy authentication checklist shows what to test first. A TLS handshake failure is a separate category. A 401, 403 or 429 from the destination calls for checking its authentication, access policy or rate limit.
Reuse HttpClient without changing proxy settings mid-session
Microsoft’s HttpClient guidelines recommend reuse to avoid unnecessary connection-pool churn. Create one client for requests that share the same handler and proxy configuration. Do not construct and dispose a new client for every request in a high-volume loop.
Because the handler owns the connection pool and proxy settings, use a separate handler/client when you genuinely need a different fixed proxy. Bound the lifetime through an application-level service or IHttpClientFactory design. Do not mutate the handler after requests have started.
When to use separate clients
Give each fixed proxy configuration its own handler and client. When an endpoint is retired, stop giving its client new work before disposing it. For a service with long-lived pools, choose a lifetime that fits DNS and endpoint changes.
Configure a named proxy client with IHttpClientFactory
In ASP.NET Core, register a named client if one partner API needs a fixed proxy. Call PartnerProxyClient.Register at startup with builder.Services, the proxy URI and credentials from protected configuration.
using System;
using System.Net;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
public static class PartnerProxyClient
{
public static void Register(
IServiceCollection services, Uri proxyAddress, NetworkCredential proxyCredentials)
{
services.AddHttpClient("PartnerApi", client =>
client.Timeout = TimeSpan.FromSeconds(15))
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
UseProxy = true,
Proxy = new WebProxy(proxyAddress) { Credentials = proxyCredentials },
ConnectTimeout = TimeSpan.FromSeconds(5),
UseCookies = false,
AllowAutoRedirect = false
});
}
}
Inject IHttpClientFactory in your service and call CreateClient("PartnerApi") for requests using that proxy. The factory manages handler reuse for the named client. Use one name per configured route and keep that set bounded. This example disables cookies and redirects for a controlled API request. See Microsoft’s handler configuration example.
Verify the exit IP
Compare the IP printed by the console example with your provider’s expected egress address from the same machine or container that will make the requests. Use the Proxy Tester and IP Location Checker for independent checks, then make a read-only call to the intended destination.
Example verification. Compiled with Roslyn and ran on .NET 10.0.14 for Windows. Six local checks used synthetic credentials and a loopback proxy. They covered HTTP Basic, a bad password, an origin challenge, a no-password route, a rejected CONNECT tunnel, and rejection of an untrusted TLS certificate after authenticated CONNECT.
Set a SOCKS5 proxy for a named HttpClient
For the named PartnerApi client above, pass a URI such as socks5://proxy.example.net:1080 as proxyAddress. Use the host and port supplied for SOCKS5. Keep the username and password in WebProxy.Credentials and leave the destination URL set to the HTTP or HTTPS API you already call.
In a local .NET 10.0.14 test, the SOCKS5 server received the destination hostname, accepted the credentials and returned an HTTP 200 test response over the tunnel. With the wrong password, the client reported ProxyTunnelError before any HTTP response. For this failure, check the endpoint scheme and proxy credentials first. See the SOCKS5 protocol specification.
Compare HTTP and SOCKS5 if both are available. See the HTTP proxy guide for HTTP proxy settings and the SOCKS5 proxy guide for choosing and testing a SOCKS5 endpoint.
Troubleshooting C# proxy errors
407 Proxy Authentication Required
Confirm username/password, source-IP authorization, and whether credentials belong on the proxy rather than the destination request. Check for extra spaces introduced by configuration.
The request bypasses the proxy
Set UseProxy = true, assign Proxy before creating the client, and verify the exit IP. Review local bypass rules and platform limitations.
Requests time out under load
Reuse clients, reduce parallelism, set cancellation, and compare direct, proxy, and target latency. A small connection pool can be saturated by unbounded tasks.
One target fails while the IP check works
The target may reject the request or require different TLS, headers, cookies, or policy-compliant access. Respect the response; a working proxy is not proof of target permission.
C# proxy checklist
- Confirm runtime and platform support.
- Create the proxy before the handler and client.
- Set
UseProxy = true. - Load credentials from protected configuration.
- Reuse one client per stable proxy configuration.
- Set timeouts and cancellation.
- Inspect status codes and exceptions separately.
- Test the exit IP and the real destination.
- Never log credentials.
C# HttpClient proxy FAQ
Where do I set the proxy in HttpClient?
Set an IWebProxy, commonly WebProxy, on HttpClientHandler.Proxy before constructing HttpClient.
Should I create a new HttpClient for every request?
No. Reuse clients for requests with the same handler and proxy configuration to avoid connection-pool churn.
How do I authenticate to the proxy?
Assign a NetworkCredential to WebProxy.Credentials, or use the provider’s documented source-IP authorization. Store secrets outside source code.
Why does the direct request work but the proxy request fail?
Check endpoint reachability, authentication, protocol, TLS, DNS, target response, and timeout. Test one layer at a time.
Test the endpoint before integrating it
Validate the proxy independently, add it to a reusable handler/client, and run a controlled target request with explicit timeout handling. More programming examples are available in our cURL proxy, Python Requests setup, Java proxy, Rust proxy, and PHP proxy guides.
