GetFromJsonAsync and ReadAsStringAsync hang with 404 repsonse

48 views Asked by At

I'm using GetFromJsonAsync and ReadAsStringAsync in C#. If I enter a URL that returns 404, there is no exception and it will just hang.

All 3 of the below functions just hang on the request. How do I force some kind of exception (or anything really) if the response is not as expected?

        private static HttpClient apiClient = new HttpClient() { BaseAddress = new Uri ("https://httpbin.org/") };
        public static async Task TestRequest() 
        {
            using HttpResponseMessage response = await apiClient.GetAsync("/bad/path");
            response.EnsureSuccessStatusCode();
            var jsonResponse = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"{jsonResponse}");
        }
1

There are 1 answers

2
Gabriel Ribeiro Rossi On BEST ANSWER

you have some options, you can get the status code and depending on the status throw a handled exception and add the try-catch block to catch internal exceptions

private static HttpClient apiClient = new HttpClient() { BaseAddress = new Uri("basePath") };

public static async Task TestRequest()
{
    try
    {
        using HttpResponseMessage response = await apiClient.GetAsync("path");
        
        //An option to EnsureSuccessStatusCode is to capture the status code and throw a custom exception.
        //if (response.StatusCode != System.Net.HttpStatusCode.OK) 
        //{
        //    thorw new Exception($"{response.StatusCode}, response.Message");
        //}

        response.EnsureSuccessStatusCode();

        var jsonResponse = await response.Content.ReadAsStringAsync();

        ...
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine($"error completing request : {ex.Message}");
    }
}