Ert*_*hko 5 c# azure asp.net-web-api azure-application-insights
请求失败时,记录HTTP请求正文的最佳方法是什么?
我通过覆盖异常记录器来记录未处理的异常:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,请求内容始终为空.我也试过这个,但是由于调用了GetBufferlessInputStream,抛出了一个不受支持的方法异常.所以这也不起作用.
我可以使用DelegatingHandler记录所有请求内容,但我只想记录由未处理的异常导致的失败请求的请求体.
有任何想法吗?
通过上面的代码,请求内容始终为空。
您可以使用 ReadAsStreamAsync 方法获取请求流并重置该流的位置。之后,您可以使用 StreamReader 读取该 steam 中的内容。下面的代码供您参考。我测试了它,在我这边工作得很好。
ExceptionTelemetry telemetry = new ExceptionTelemetry(context.Exception);
//Get request stream and reset the position of this stream
Stream requestBodyStream = context.Request.Content.ReadAsStreamAsync().Result;
requestBodyStream.Position = 0;
string requestBody = string.Empty;
using (StreamReader sr = new StreamReader(requestBodyStream))
{
requestBody = sr.ReadToEnd();
}
telemetry.Properties.Add("Request Body", requestBody);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1660 次 |
| 最近记录: |