'Why HttpClient.GetFromJsonAsync doesn't throw an exception when the response is HTML instead of JSON?

I'm learning Blazor. I have created a Blazor WASM App with the "ASP.NET Core Hosted" option. So I have 3 projects in the solution: Client, Server and Shared.

The following code is in the Client project and works perfectly when the endpoint is correct (obviously). But at some point I made a mistake and messed up the request URI, and then I noticed that the API returned an HTML page with code 200 OK (as you can see in the Postman screenshot below the code).

I expected one of my try-catches to get this, but the debugger jumps to the last line (return null) without throwing an exception.

My first question is why?

My second question is how can I catch this?

I know fixing the endpoint fixes everything, but would be nice to have a catch that alerts me when I have mistyped an URI.

Thanks.

private readonly HttpClient _httpClient;
public async Task<List<Collaborator>> GetCollaborators()
{
    string requestUri = "api/non-existent-endpoint";
    try
    {
        var response = await _httpClient.GetFromJsonAsync<CollaboratorsResponse>(requestUri);
        if (response == null) 
        {
            // It never enters here. Jumps to the last line of code.
        }
        return response.Collaborators;
    }
    catch (HttpRequestException)
    {
        Console.WriteLine("An error occurred.");
    }
    catch (NotSupportedException)
    {
        Console.WriteLine("The content type is not supported.");
    }
    catch (JsonException)
    {
        Console.WriteLine("Invalid JSON.");
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    return null;
}

Postman Screenshot



Solution 1:[1]

it is a never good idea to use GetFromJsonAsync, You are not the first who are asking about the strange behavior. Try to use GetAsync. at least you will now what is going on.

    var response = await client.GetAsync(requestUri);
    var statusCode = response.StatusCode.ToString();
    if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<CollaboratorsResponse>(stringData);
        ... your code
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1