Configuring proxy settings for HttpClient
in C# is essential when you need to route HTTP requests through a proxy server for security, anonymity, or network access requirements.
Basic Proxy Configuration
Use HttpClientHandler
with the Proxy
property to configure proxy settings:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class HttpClientProxyExample
{
public static HttpClient CreateHttpClientWithProxy()
{
// Configure proxy settings
var proxy = new WebProxy("http://proxy-server.com:8080")
{
// Optional: Set credentials for authenticated proxies
Credentials = new NetworkCredential("username", "password"),
// Optional: Bypass proxy for local addresses
BypassProxyOnLocal = true
};
// Create handler with proxy configuration
var handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true
};
return new HttpClient(handler);
}
}
Different Proxy Types
HTTP Proxy
var proxy = new WebProxy("http://proxy.example.com:8080");
HTTPS Proxy
var proxy = new WebProxy("https://secure-proxy.example.com:443");
SOCKS Proxy (via SocketsHttpHandler)
// For .NET 5+ and SOCKS proxy support
var handler = new SocketsHttpHandler()
{
Proxy = new WebProxy("socks5://socks-proxy.example.com:1080")
};
var client = new HttpClient(handler);
Advanced Configuration Options
Proxy with Authentication
public static HttpClient CreateAuthenticatedProxyClient()
{
var proxy = new WebProxy("http://proxy.example.com:8080")
{
Credentials = new NetworkCredential("proxyUser", "proxyPass"),
// Use default credentials (current Windows user)
// Credentials = CredentialCache.DefaultCredentials
};
var handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
PreAuthenticate = true // Send credentials with first request
};
return new HttpClient(handler);
}
Bypass Proxy for Specific Addresses
var proxy = new WebProxy("http://proxy.example.com:8080")
{
BypassProxyOnLocal = true,
// Bypass proxy for specific addresses
BypassList = new[] {
"*.local.com",
"192.168.*",
"localhost"
}
};
System Proxy Configuration
// Use system proxy settings
var handler = new HttpClientHandler()
{
UseProxy = true,
Proxy = null // Uses system default proxy
};
var client = new HttpClient(handler);
Complete Example with Error Handling
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
public class ProxyHttpClientService
{
private readonly HttpClient _httpClient;
public ProxyHttpClientService(string proxyUrl, string username = null, string password = null)
{
var proxy = new WebProxy(proxyUrl);
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
proxy.Credentials = new NetworkCredential(username, password);
}
var handler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true,
ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true // Only for testing
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
}
public async Task<string> GetAsync(string url)
{
try
{
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException ex)
{
throw new Exception($"HTTP request failed: {ex.Message}", ex);
}
catch (TaskCanceledException ex)
{
throw new Exception($"Request timeout: {ex.Message}", ex);
}
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
// Usage example
class Program
{
static async Task Main(string[] args)
{
var service = new ProxyHttpClientService(
"http://proxy.example.com:8080",
"username",
"password"
);
try
{
string content = await service.GetAsync("https://api.example.com/data");
Console.WriteLine(content);
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
service.Dispose();
}
}
}
Using Dependency Injection (ASP.NET Core)
// In Startup.cs or Program.cs
services.AddHttpClient("ProxyClient", client =>
{
// Configure client settings
})
.ConfigurePrimaryHttpMessageHandler(() =>
{
var proxy = new WebProxy("http://proxy.example.com:8080")
{
Credentials = new NetworkCredential("username", "password")
};
return new HttpClientHandler()
{
Proxy = proxy,
UseProxy = true
};
});
// In your service or controller
public class MyService
{
private readonly HttpClient _httpClient;
public MyService(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient("ProxyClient");
}
}
Important Considerations
- HttpClient Reuse: Always reuse
HttpClient
instances to avoid socket exhaustion - Disposal: Properly dispose of
HttpClient
andHttpClientHandler
when done - Timeout Configuration: Set appropriate timeouts for proxy connections
- Security: Never hardcode credentials in production code
- SSL Validation: Be cautious when bypassing SSL certificate validation
- Proxy Authentication: Test authentication requirements with your proxy provider
Common Proxy Configuration Scenarios
- Corporate Networks: Use system proxy with Windows authentication
- Web Scraping: Rotate between multiple proxy servers for rate limiting
- Security Testing: Route traffic through security analysis proxies
- Geographic Testing: Use proxies in different regions for location-based testing