Skip to content

CSharp Async HttpClient Example

Joe Care edited this page Dec 22, 2025 · 1 revision

C# Async/Await: Simple HTTP Request with HttpClient

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:


1. Setup

Create a console app (see CSharp-AsyncAwait-Basics.md), then add this code to Program.cs.


2. Example: fetch JSON from a web API

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 Main allows await in the entry point.
  • HttpClient.GetAsync and ReadAsStringAsync are awaited.
  • EnsureSuccessStatusCode throws if the status code is not 2xx.

3. Next steps

  • Modify the URL and inspect different JSON responses.
  • Add JSON deserialization using System.Text.Json.
  • Combine with exception patterns from CSharp-Exceptions-TryCatch.md.

Clone this wiki locally