Before we get back to coding, visit the Free Proxy List website and select a proxy that is closest to your location. For this example, I will select a proxy located in Germany. Write down the IP address and the port of the selected proxy.
For using a proxy with HttpClient, we need to create a HttpClientHandler instance. Within this instance, we set two properties: the proxy URL and the port and `ServerCertificateCustomValidationCallback`. That’s a long name for a variable but this is important.
`ServerCertificateCustomValidationCallback` tells the HttpClientHandler to ignore any HTTPS certificate errors. You might be wondering why you have to do this.
The proxy server intercepts and inspects the traffic, including the HTTPS certificate, before forwarding it to the target server. As a result, the certificate presented by the target server to the proxy server may be different from the one presented to the client.
By default, the HttpClient and other similar libraries will validate the certificate presented by the target server, and if it is not valid or doesn't match the one presented to the client, it will raise an exception. This is where the certificate errors come from.
Ignoring the HTTPS certificate errors when using proxy mode allows the request to continue even if the certificate is not valid, which is useful in some cases where the certificate is intercepted and modified by the proxy server.
It’s time to write the code. Let’s start with the HttpClientHandler instance:
using System.Net;
using var httpClientHandler = new HttpClientHandler
{
Proxy = new WebProxy("http://5.9.139.204:24000"),
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
We need to provide the HttpClient class with an instance of the HttpClientHandler. The modified client code should appear as follows:
using var client = new HttpClient(httpClientHandler);
The entire code should look like this:
using System.Net;
using var httpClientHandler = new HttpClientHandler
{
Proxy = new WebProxy("http://5.9.139.204:24000"),
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};
using var client = new HttpClient(httpClientHandler);
var result = await client.GetStringAsync("https://api.ipify.org?format=json");
Console.WriteLine(result);
Running the code will return the proxy IP address instead of your IP address. You can open the ipify URL in your browser and compare the results.