How do I send custom headers with every request using HttpClient (C#)?

In C#, HttpClient is a class provided by the .NET framework that enables you to send HTTP requests and receive HTTP responses. If you want to send custom headers with every request using HttpClient, you can do so by adding those headers to the DefaultRequestHeaders property of your HttpClient instance. This ensures that the specified headers are included in every outgoing request made by that HttpClient.

Here's an example of how you can achieve this:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var httpClient = new HttpClient())
        {
            // Set up your custom headers to be sent with every request
            httpClient.DefaultRequestHeaders.Add("Custom-Header", "HeaderValue");
            httpClient.DefaultRequestHeaders.Add("User-Agent", "MyApp/1.0");

            // Optionally, you can also set up headers that have multiple values
            httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US");
            httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-GB");

            // Your target URI
            Uri targetUri = new Uri("https://example.com/api/data");

            // Send a GET request
            HttpResponseMessage response = await httpClient.GetAsync(targetUri);

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode}");
            }
        }
    }
}

In this example, we're adding a custom header named Custom-Header with the value HeaderValue and setting the User-Agent to MyApp/1.0. These headers will be included in the HTTP GET request we're sending to https://example.com/api/data.

Please note that some headers are considered restricted and cannot be set using DefaultRequestHeaders. Instead, they need to be set on the request message itself. Here's an example of how you can do that:

using (var httpClient = new HttpClient())
{
    // Your target URI
    Uri targetUri = new Uri("https://example.com/api/data");

    // Create a HttpRequestMessage
    using (var request = new HttpRequestMessage(HttpMethod.Get, targetUri))
    {
        // Add restricted headers directly to the request message
        request.Headers.Add("Connection", "keep-alive");

        // Send the request
        HttpResponseMessage response = await httpClient.SendAsync(request);

        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
        else
        {
            Console.WriteLine($"Error: {response.StatusCode}");
        }
    }
}

In this example, a Connection header, which is a restricted header, is being added directly to the HttpRequestMessage object before sending the request.

It's important to manage the lifetime of HttpClient correctly. In most cases, it's recommended to use a single instance of HttpClient for the entire lifetime of the application, which can be achieved by using dependency injection or by creating a static singleton instance. Creating a new HttpClient instance for each request can lead to socket exhaustion under heavy load.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon