Using HttpClient with Sync and Async in C#

By FoxLearn 1/9/2025 2:27:13 AM   134
The System.Net.Http.HttpClient() provides a robust HTTP client, but using it can be a challenge, especially if you're not familiar with asynchronous programming like I wasn't.

To help, here's a quick reference guide on how to navigate Task<>, async, and await when working with HttpClient().

I've removed HttpClient from the using statement. This change prevents creating a new instance of HttpClient for each request, which can lead to socket exhaustion.

For example, Using HttpClient GET with a Return Value

private static readonly HttpClient _httpClient = new HttpClient();

public static async Task<string> GetAsync(string queryString)
{
    string authUserName = "user";
    string authPassword = "password";
    string url = "https://foxlearn.com";

    // Include these lines for basic authentication
    var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
    _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

    // The actual GET request
    using (var response = await _httpClient.GetAsync($"{url}{queryString}"))
    {
        string content = await response.Content.ReadAsStringAsync();
        return content;
    }
}

Usage:

// Synchronous code:
string queryString = "?param=example";
string result = GetAsync(queryString).Result;

// Asynchronous code:
string queryString = "?param=example";
string result = await GetAsync(queryString);

For example, Using HttpClient PUT “Fire-and-Forget” Without Return Value

private static readonly HttpClient _httpClient = new HttpClient();

public static async Task PutAsync(string postData)
{
    string authUserName = "user";
    string authPassword = "password";
    string url = "https://someurl.com";

    // Include these lines for basic authentication
    var authToken = Encoding.ASCII.GetBytes($"{authUserName}:{authPassword}");
    _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));

    // The actual PUT request with error handling
    using (var content = new StringContent(postData))
    {
        var response = await _httpClient.PutAsync(url, content);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            return;
        }
        else
        {
            // Log the status code and response content
            string responseContent = await response.Content.ReadAsStringAsync();
            // Log the details
        }
    }
}

Usage:

// Call the method asynchronously and do not wait for the result (fire-and-forget)
PutAsync("data");

// If you need to wait for the completion, use .Wait()
PutAsync("data").Wait();

This should give you a simple and clear way to work with the HttpClient class using async and await.