make a http request with a custom header in csharp

To make an HTTP request with a custom header in C#, you can use the HttpClient class from the System.Net.Http namespace. Here's an example:

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

class Program
{
    static async Task Main(string[] args)
    {
        using var httpClient = new HttpClient();

        // Set the custom header
        httpClient.DefaultRequestHeaders.Add("Custom-Header", "Value");

        try
        {
            var response = await httpClient.GetAsync("http://example.com");

            response.EnsureSuccessStatusCode();

            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine(content);
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}
668 chars
30 lines

In this example, we create a new HttpClient instance and set the custom header using the DefaultRequestHeaders.Add method. We then make an HTTP GET request to http://example.com using the GetAsync method. If the request is successful, we read the content of the response using the ReadAsStringAsync method and print it to the console.

Note that you can set any number of custom headers using this method. Simply call Add with the header name and value that you want to set.

gistlibby LogSnag