是否可以在 Application Insights 中查看请求的响应正文?我看过很多关于请求正文的问题/文章,但没有发现关于响应正文的指导。
我正在构建一个 MVC 核心 2.1 Web Api。
这是我的代码,从流创建读取器时出现异常,即“流不可读”。.
public class ResponseBodyInitializer : ITelemetryInitializer
{
readonly IHttpContextAccessor httpContextAccessor;
public ResponseBodyInitializer(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void Initialize(ITelemetry telemetry)
{
if (telemetry is RequestTelemetry requestTelemetry)
{
HttpContext httpContext = httpContextAccessor.HttpContext;
HttpRequest request = httpContext.Request;
HttpResponse response = httpContext.Response;
if (request.Method == HttpMethods.Post ||
request.Method == HttpMethods.Put)
{
//Log the response body
if (httpContext.Response.HasStarted)
{
const string responseBody = "ResponseBody";
if (requestTelemetry.Properties.ContainsKey(responseBody))
{
return;
}
try
{
var stream = new StreamReader(response.Body);
var body = stream.ReadToEnd();
response.Body.Position = 0;
requestTelemetry.Properties.Add(responseBody, body);
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
}
慕工程0101907
慕丝7291255
三国纷争
相关分类