Using HttpClient with Sync and Async in C#
By FoxLearn 1/9/2025 2:27:13 AM 249
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
.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#