-
Notifications
You must be signed in to change notification settings - Fork 2
CSharp Async HttpClient Example
Joe Care edited this page Dec 22, 2025
·
1 revision
This lesson shows how to use async/await with HttpClient to fetch data from a web API.
Related wiki pages:
- Async basics:
CSharp-AsyncAwait-Basics.md - Tasks and
Task.Run:CSharp-Async-Tasks-TaskRun.md - Exceptions:
CSharp-Exceptions-TryCatch.md
Official docs:
Create a console app (see CSharp-AsyncAwait-Basics.md), then add this code to Program.cs.
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
try
{
string url = "https://jsonplaceholder.typicode.com/todos/1";
string content = await FetchAsync(url);
Console.WriteLine("Response content:");
Console.WriteLine(content);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
}
}
static async Task<string> FetchAsync(string url)
{
using var httpClient = new HttpClient();
using HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
return content;
}
}Key points:
-
async Task Mainallowsawaitin the entry point. -
HttpClient.GetAsyncandReadAsStringAsyncare awaited. -
EnsureSuccessStatusCodethrows if the status code is not 2xx.
- Modify the URL and inspect different JSON responses.
- Add JSON deserialization using
System.Text.Json. - Combine with exception patterns from
CSharp-Exceptions-TryCatch.md.