我想在依赖项表 Application Insight 中跟踪我的httpclient请求的响应正文。我的应用程序使用 .NET 框架 4.8 运行我创建了一个 Initializer 来使用以下代码跟踪 Dependencies 遥测:
public class TrackResponseBody : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
var requestTelemetry = telemetry as DependencyTelemetry;
if (requestTelemetry == null)
return;
if (requestTelemetry.TryGetOperationDetail("HttpResponse", out var responseObj))
{
var response = responseObj as HttpWebResponse;
if (response != null)
{
using (var stream = response.GetResponseStream())
{
var reader = new StreamReader(stream);
string result = reader.ReadToEnd();
requestTelemetry.Properties["ResponseBody"] = result;
}
}
}
}
}
但是当我尝试调用时reader.ReadToEnd()
,我的代码会生成此异常:System.NotSupportedException: 'The stream does not support concurrent IO read or write operations.'
如果我不尝试获取正文响应,则此代码在应用程序洞察依赖项日志中正确写入。
这就是我实现我的方式HttpClient
:
var client_ = new HttpClient();
client_.BaseAddress = new Uri("https://www.google.com");
using (var request_ = new HttpRequestMessage())
{
request_.Method = new HttpMethod("GET");
var response_ = await client_.SendAsync(request_).ConfigureAwait(false);
var responseData_ = await response_.Content.ReadAsStringAsync().ConfigureAwait(false);
}
有没有办法获得我的HttpClient的正文响应?