C#C
C#3y ago
fooo1

❔ ✅ Why doesn't this basic HttpClient GET request doesn't work as expected?

I do not get anything past making a request. Neither an exception, nor an exception. I'm guessing it's because I'm not properly waiting for async to complete - but in that case what is it lacking?

Program.cs
HttpClientLib httpClientLib = new();
httpClientLib.RequestGet();


HttpClientLib.cs
using System.Net.Http;

public class HttpClientLib
{
    public async void RequestGet()
    {
        try
        {
            using (var client = new HttpClient()) {
                var url = "https://dummy.restapiexample.com/api/v1/employees";
                HttpResponseMessage response = await client.GetAsync(url);
                Console.WriteLine(response.StatusCode);
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Generic exception caught: {ex.Message}");
        }
    }
}
Was this page helpful?