请求失败时记录HTTP请求主体的最佳方式是什么?在Application Insights中对失败的请求记录请求正文的最佳做法是什么?
我通过重写异常记录仪记录未处理的异常:
public class AiExceptionLogger : ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
if (context != null && context.Exception != null)
{
ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);
// the requestBody is always empty because the stream is non-rewinadable?
string requestBody = context.Request.Content.ReadAsStringAsync().Result;
telemetry.Properties.Add("Request Body", requestBody);
Logger.LogException(telemetry);
}
base.Log(context);
}
}
与上面的代码,请求内容始终是空的。我也尝试过this,但是由于调用了GetBufferlessInputStream而引发了不支持的方法异常。所以这也行不通。
我可以使用DelegatingHandler记录所有请求内容,但我只想记录由未处理的异常导致失败请求的请求正文。
任何想法?
即使我使用了Mitch Stewart的CopyTo方法,我也接受了您的答案。但由于他的代码不完整,需要修改才能工作,所以我无法将其标记为正确答案:) –
@ErtayShashko我不确定为什么这是可接受的答案,因为它不起作用。您无法重置该位置。 – Phill
@Phill,如果您无法在您的环境中重置requestBodyStream的位置,则可以将其复制到MemoryStream并重置MemoryStream的位置。然后我们可以从MemoryStream读取数据。 MemoryStream ms = new MemoryStream(); requestBodyStream.CopyTo(ms); ms.Position = 0; – Amor