How to Set a Proxy Using HttpClient in .NET With C#

Master C# HttpClient proxy integration with this step-by-step guide. Learn setup, authentication, SSL handling, and IP rotation for secure web requests.
12 min read
How to Set a Proxy Using HttpClient blog image

By the end of this HttpClient C# proxy integration guide, you will know:

  • What HttpClient is and its role in making HTTP requests in .NET
  • Why you should use a proxy in C#
  • How to set up a proxy in HttpClient
  • How to handle proxy authentication, SSL certificate errors, and IP rotation with HttpClient.

Let’s dive in!

What Is HttpClient in .NET?

HttpClient is a class for making HTTP requests and receiving HTTP responses in .NET. It is part of the System.Net.Http namespace, representing the default HTTP client in .NET—and, therefore, C#.

HttpClient supports:

  • All HTTP methods, including GET, POST, PUT, PATCH, and DELETE
  • Asynchronous communication
  • Headers and cookie customization
  • Request body customization
  • Proxy integration

These features, along with its official support in the .NET Standard Library, make HttpClient a popular choice for HTTP requests in C#.

Why You Need to Set a Proxy in C# HttpClient

When working with web scraping, data gathering, or other internet-related tasks, protecting your online identity is key. One way to achieve that is by using routing your traffic through a proxy server.

A proxy server acts as an intermediary between you and the destination site, providing these benefits to HttpClient:

  • Hidden IP and location: The destination servers see the proxy’s IP, not yours.
  • Enhanced confidentiality: Proxies add a layer of privacy by masking your real identity and making it harder to track you.
  • Avoid IP bans: Proxies help you circumvent rate limiters, which is fundamental in web scraping with C#.
  • Bypass geo-restrictions: You can use proxy servers located in specific regions to access geo-restricted content from your home.

Thus, using proxies in HttpClient not only increases your online security but also enhances the reliability of your scraping tasks.

Set Up a Proxy with HttpClient in C#: Step-By-Step Guide

Follow the steps below to learn how to integrate a proxy in HttpClient in .NET using C#.

Prerequisites

Before you begin, make sure that you meet the following prerequisites:

If you do not have the required tools, download them using the link above and follow the installation wizard.

Step #1: Project Set Up

Create a new folder for your .NET project and navigate to it in the terminal with the following commands:

mkdir httpclient-proxy
cd httpclient-proxy

Next, initialize a new .NET Console application inside it:

dotnet run console

The output should be:

The template "Console App" was created successfully.

Now, open the project folder in your IDE:

Program.cs in your C# Project

You should see the files generated by the template, with Program.cs being the most important. Currently, it contains a simple “Hello, World!” script. At the end of this section, that will be a C# HttpClient proxy integration script.

To ensure everything works as expected, try to launch the C# application with:

dotnet run

The result should be:

Hello, World!

Great! You now have a working C# project in Visual Studio Code.

Step #2: Set Up HttpClient

Add the following lines of code to Program.cs to send a request using HttpClient:

using System.Net;

class Program
{
  static async Task Main()
  {
    // initialize an HttpClient instance
    using HttpClient client = new HttpClient();

    // the target URL
    string url = "https://httpbin.org/ip";

    // send an async GET request to the endpoint
    HttpResponseMessage response = await client.GetAsync(url);

    // read the response content as a string
    string responseBody = await response.Content.ReadAsStringAsync();

    // print the response to the console
    Console.WriteLine(responseBody);
  }
}

The snippet initializes an HttpClient instance and uses its GetAsync() method to connect to the /ip GET endpoint from the HTTPBin.io project. That API returns the caller’s IP address, making it a perfect target for checking whether proxy integration works as expected. The reason? Once you integrate a proxy into HttpClient, the IP returned by the /ip endpoint must be different from your original IP.

If you run the script, the output should be something like:

{
  "origin": "55.17.80.196"
}

The IP address contained in origin represents your exit IP.

Amazing! Time to get a valid proxy URL.

Step #3: Retrieve a Proxy

To integrate a proxy into HttpClient, you first need access to a proxy server.

Many online portals offer free proxy URLs, but be cautious—running a proxy infrastructure is expensive. If a service is offering free proxies, consider what their business model might be. Often, they engage in data stealing or other questionable practices.

For that reason, it is best to use free proxies only for learning purposes and avoid them for production use!

If you need reliable proxies, consider reputable providers that offer free trials or limited free plans. For example, you can try our free proxies.

Now, a typical proxy URL follows this format:

<protocol>://<host>:<port>

Where:

  • protocol specifies the proxy type (e.g., http, https, socks5, etc.)
  • host: The domain or IP address of the proxy server
  • port: The port number through which traffic is routed

In this example, we will assume that the proxy URL is:

http://66.29.154.103:3128

Store that in a variable in Program.cs:

string proxyUrl = "http://66.29.154.103:3128";

Time to see how to use a proxy with HttpClient!

Step #4: Proxy Integration

HttpClient enables you to specify a proxy through the HttpClientHandler class. That provides low-level control over HTTP requests sent by an HttpClient instance.

In particular, HttpClientHandler has a Proxy property that accepts a WebProxy object containing proxy server settings:

WebProxy proxy = new WebProxy
{
  Address = new Uri(proxyUrl),
};

Then, pass proxy to an HttpClientHandler instance:

HttpClientHandler handler = new HttpClientHandler
{
    Proxy = proxy,
};

And finally pass HttpClientHandler to the HttpClient constructor:

using HttpClient client = new HttpClient(handler);

Wonderful! HttpClient C# proxy integration completed.

Step #5: Put It All Together

Your final HttpClient proxy integration script should contain:

using System.Net;

class Program
{
  static async Task Main()
  {
    // initialize a new proxy object
    string proxyUrl = "http://66.29.154.103:3128"; // replace with a valid proxy URL
    WebProxy proxy = new WebProxy
    {
      Address = new Uri(proxyUrl),
    };

    // define an HTTP client handler with the given proxy
    HttpClientHandler handler = new HttpClientHandler
    {
      Proxy = proxy,
    };

    // initialize an HttpClient instance with proxy integration
    using HttpClient client = new HttpClient(handler);

    // the target URL
    string url = "https://httpbin.org/ip";

    // send an async GET request to the endpoint
    HttpResponseMessage response = await client.GetAsync(url);

    // read the response content as a string
    string responseBody = await response.Content.ReadAsStringAsync();

    // print the response to the console
    Console.WriteLine(responseBody);
  }
}

Execute the script:

dotnet run

The result should be:

{
  "origin": "66.29.154.103"
}

Note that the origin attribute in the response from the /ip endpoint displays the IP address of the proxy server. This confirms that your real IP has been successfully hidden behind the proxy.

Warning: Free proxy servers are usually short-lived and unreliable. By the time you read this guide, the chosen proxy will no longer work. To test the code, replace proxyUrl with a valid, working proxy URL before running the script.

Advanced Use Cases for HttpClient Proxy Integration

You just learned the basics of proxy integration with HttpClient in C#, but there are other more advanced scenarios to consider.

Proxy Authentication

Premium proxies are protected with authentication to restrict access to authorized users. In particular, the URL of an authenticated proxy follows this format:

<protocol>://<username>:<password>@<host>:<port>

Where username and password are the credentials used for authentication.

In HttpClient, proxy authentication is handled using the Credentials property of WebProxy. That property accepts a NetworkCredential object as follows:

WebProxy proxy = new WebProxy
{
  Address = new Uri(proxyUrl),
  // specify proxy authentication
  Credentials = new NetworkCredential("<username>", "<password>"),
};

Extract <username> and <password> from your authenticated proxy URL and replace them in the above code.

So, the code for authenticated proxy integration becomes:

using System.Net;

class Program
{
  static async Task Main()
  {
    // initialize a new proxy object
    string proxyUrl = "<protocol>://<host>:<port>";
    WebProxy proxy = new WebProxy
    {
      Address = new Uri(proxyUrl),
      // specify proxy authentication
      Credentials = new NetworkCredential("<username>", "<password>"),
    };

    // define an HTTP client handler with the given proxy
    HttpClientHandler handler = new HttpClientHandler
    {
      Proxy = proxy,
    };

    // initialize an HttpClient instance with authenticated proxy integration
    using HttpClient client = new HttpClient(handler);

    // the target URL
    string url = "https://httpbin.org/ip";

    // send an async GET request to the endpoint
    HttpResponseMessage response = await client.GetAsync(url);

    // read the response content as a string
    string responseBody = await response.Content.ReadAsStringAsync();

    // print the response to the console
    Console.WriteLine(responseBody);
  }
}

Avoid SSL Certificate Issues

When setting up a proxy in HttpClient, your requests may fail due to the SSL certificate verification error below:

Unhandled exception. System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot

This typically happens when the proxy uses a self-signed SSL certificate.

If you trust your proxy server—and only in that scenario, you can disable SSL verification to bypass this issue using the following approach:

HttpClientHandler handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
  return true;
};

using HttpClient client = new HttpClient(handler);

The above snippet overrides the default certificate validation behavior with a custom callback that always returns true.

Note: Disabling SSL verification makes your connection vulnerable to MITM (Man-in-the-Middle) attacks. Only use this approach if you fully trust your proxy and are aware of the security risks.

Implement Proxy Rotation

If you rely on the same proxy server repeatedly, the target site may eventually block its IP address. To avoid that, you can rotate your proxy servers for each request, so that your requests use a different proxy server each time.

To implement proxy rotation, follow this procedure

  1. Populate a list with many proxy URLs
  2. Randomly pick a proxy URL before each request
  3. Set the chosen proxy URL in HttpClient

The above algorithm translates into the following snippet:

using System.Net;

class Program
{  
  static async Task Main()
  {
    // get a random proxy URL
    string selectedProxyUrl = GetRandomProxyUrl();

    // configure the random proxy
    HttpClientHandler handler = new HttpClientHandler
    {
      Proxy = new WebProxy
      {
        Address = new Uri(selectedProxyUrl),
      },
    };

    // perform a GET request through the random proxy
    using HttpClient client = new HttpClient(handler);
    string url = "https://httpbin.org/ip";
    HttpResponseMessage response = await client.GetAsync(url);

    // read the response content as a string and print it
    string responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseBody);
  }

  static string GetRandomProxyUrl()
  {
    // the list of proxy URL to rotate from
    List<string> proxyUrls = new List<string>
        {
            "<protocol_1>://<proxy_host_1>:<port_1>",
            // ...
            "<protocol_n>://<proxy_host_n>:<port_n>",
        };

    // return a random proxy URL from the list
    Random random = new Random();
    int index = random.Next(proxyUrls.Count);
    return proxyUrls[index];
  }
}

The main drawbacks of this approach are:

  • It involves boilerplate code
  • It requires access to a pool of reliable proxy servers, which usually comes at a cost

Luckily, there is a more efficient solution to rotate an IP address in C#!

Bright Data provides rotating proxies that automatically rotate the exit IP addresses, eliminating the need for manual proxy rotation. They boast around 100 million IPs, are available in 195 countries, have exceptional network uptime, and guarantee a 99.9% success rate.

In the next chapter, you will learn how to get started with Bright Data’s rotating proxies in HttpClient.

Use a Bright Data Proxy in HttpClient

Bright Data operates one of the largest proxy servers in the world, serving Fortune 500 companies and over 20,000 customers. This worldwide proxy network includes:

Follow the steps below to learn how to use Bright Data’s residential proxies with HttpClient in C#.

If you already have an account, log in to Bright Data. If not, create an account for free. Once logged in, you will be directed to your user dashboard:

Bright Data's dashboard after login

Click the “View proxy products” button to proceed:

Clicking on view proxy products

You will be redirected to the “Proxies & Scraping Infrastructure” page:

Proxies & Scraping Infrastructure main page

Scroll down and find the “Residential Proxies” card. Click the “Get started” button:

Getting started with residential proxies

On the residential proxy configuration page, follow the wizard to customize the service based on your needs. If you have any questions, feel free to reach out to the 24/7 support:

Customizing the service based on your needs

Go to the “Access parameters” tab to retrieve your proxy’s host, port, username, and password:

The access parameters for your new zone

Note that the “Host” field includes the port.

Now that you have the necessary details, build your proxy URL and use it with the WebProxy object in C#:

WebProxy proxy = new WebProxy
{
  Address = new Uri("http://<brightdata_proxy_host>:<brightdata_proxy_port>"),
  Credentials = new NetworkCredential("<brightdata_proxy_username>", "<brightdata_proxy_password>"),
};

Replace the <...> placeholders with your Bright Data’s proxy info.

Toggle the “Active proxy” setting, follow the remaining instructions, and you are all set!

Use the following C# code snippet to integrate Bright Data’s proxy into HttpClient:

using System.Net;

class Program
{
  static async Task Main()
  {
    // initialize a new proxy object
    WebProxy proxy = new WebProxy
    {
      // TODO: replace the placeholders with your Bright Data's proxy info
      Address = new Uri("http://<brightdata_proxy_host>:<brightdata_proxy_port>"),
      Credentials = new NetworkCredential("<brightdata_proxy_username>", "<brightdata_proxy_password>"),
    };

    // define an HTTP client handler with the given proxy
    HttpClientHandler handler = new HttpClientHandler
    {
      Proxy = proxy,
    };

    // disable SSL verification
    handler.ClientCertificateOptions = ClientCertificateOption.Manual;
    handler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
    {
      return true;
    };

    // initialize an HttpClient instance with proxy integration
    using HttpClient client = new HttpClient(handler);

    // the target URL
    string url = "https://httpbin.org/ip";

    // send an async GET request to the endpoint
    HttpResponseMessage response = await client.GetAsync(url);

    // read the response content as a string
    string responseBody = await response.Content.ReadAsStringAsync();

    // print the response to the console
    Console.WriteLine(responseBody);
  }
}

Every time you run the above script, you will see a different exit IP.

HttpClient proxy rotation has never been easier with Bright Data’s auto-rotating proxies!

Conclusion

In this proxy integration tutorial, you learned why using proxies is important and how to integrate them with HttpClient in C#. You discovered how easy it is to set up a proxy in HttpClient, the default HTTP client library in .NET.

Through this guide, you also understood why relying on free proxy services is risky. Instead, you need to use reliable proxies from a reputable proxy provider. And when it comes to the best rotating proxy provider on the market, look no further than Bright Data.

Create an account and start testing our proxies for free today!

No credit card required