Search code examples
c#dotnet-httpclient

Is there a need to check `IsSuccessStatusCode` after `ReadAsStringAsync`?


consider:

HttpClient client = new HttpClient();
var response = await client.GetAsync("url");
if (response.IsSuccessStatusCode) return false;
var getResponsestring = await response.Content.ReadAsStringAsync();
// check response.IsSuccessStatusCode again ??

Do I now need to check IsSuccessStatusCode again ? or is exception handling covers all errors ?

That is can IsSuccessStatusCode be true after GetAsync but false after ReadAsStringAsync ?


Solution

  • You don't have to check the IsSuccessStatusCode property after calling ReadAsStringAsync, once after invoking client.GetAsync is enough. ReadAsStringAsync won't change the value of IsSuccessStatusCode.

    As the docs state:

    Gets a value that indicates whether the HTTP response was successful.