Skip to content

Latest commit

 

History

History
48 lines (32 loc) · 2.27 KB

File metadata and controls

48 lines (32 loc) · 2.27 KB

HCR061

Check HTTP response success before reading content.

Why

HttpClient does not throw for unsuccessful HTTP status codes. Reading response content without first checking success can silently treat errors, throttling responses, or upstream failures as valid payloads.

Bad

var response = await client.GetAsync("https://example.com/orders", cancellationToken);
var json = await response.Content.ReadAsStringAsync(cancellationToken);

Better

var response = await client.GetAsync("https://example.com/orders", cancellationToken);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(cancellationToken);
var response = await client.GetAsync("https://example.com/orders", cancellationToken);
if (!response.IsSuccessStatusCode)
{
    return null;
}

var json = await response.Content.ReadAsStringAsync(cancellationToken);

Current Detection

The implementation reports local HttpResponseMessage variables initialized from awaited visible HttpClient calls such as GetAsync(...), PostAsync(...), or SendAsync(...) when the same block reads response.Content through common content read methods before any visible success handling on that response local.

Success handling is recognized when the response local calls EnsureSuccessStatusCode() or when IsSuccessStatusCode or StatusCode is read before content is read. The analyzer stops following the original response when the local is reassigned before content is read, and it does not report when the response is returned or otherwise no content read is visible in the same block. Resolved custom HttpClient and response-like types are skipped.

Suppression

Suppress only when unsuccessful status codes are intentionally valid payload carriers and the status is handled outside the visible code path.

References