I have a service which is consuming an SMS REST API using HttpClient:
HttpClient http = this._httpClientFactory.CreateClient();
// Skipped: setup HttpRequestMessage
using (HttpResponseMessage response = await http.SendAsync(request))
{
try
{
_ = response.EnsureSuccessStatusCode();
}
catch (HttpRequestException)
{
string responseString = await response.Content.ReadAsStringAsync(); // Fails with ObjectDisposedException
this._logger.LogInformation(
"Received invalid HTTP response status '{0}' from SMS API. Response content was {1}.",
(int)response.StatusCode,
responseString
);
throw;
}
}
The API returns an error, but I would like to be able to log it. So I need to log both the failing status code (which I can read from response.StatusCode) and the associated content (which may contain additional error useful details).
This code fails on the instruction await response.Content.ReadAsStringAsync() with this exception:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.HttpConnection+HttpConnectionResponseContent'.
Module "System.Net.Http.HttpContent", in CheckDisposed
Module "System.Net.Http.HttpContent", in ReadAsStringAsync
Some sources suggest that you shouldn't read the response content when the status code is not in the success range (200-299), but what if the response really contains useful error details?
.NET version used: .NET Core 2.1.12 on AWS lambda linux runtime.
EnsureSuccessStatusCode()is disposing the response?