我有一个服务,它正在使用 HttpClient
调用短信 REST API:
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;
}
}
API返回了错误,但我希望能够记录它。因此,我需要同时记录失败的状态码(可以从
response.StatusCode
中读取)和相关内容(可能包含其他有用的错误详情)。这段代码在指令
await response.Content.ReadAsStringAsync()
上失败,并提示以下异常信息:
一些来源表示,在状态码不在成功范围(200-299)内时,您不应该读取响应内容,但如果响应确实包含有用的错误详细信息怎么办?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
.NET版本:AWS Lambda Linux运行时上的.NET Core 2.1.12。
EnsureSuccessStatusCode()
会释放响应? - Maxime Rossini