无法获得响应正文以将其记录在应用程序见解中

时间:2019-04-03 10:24:42

标签: c# .net-core middleware azure-application-insights

为了将response bodyHttpContext登录到应用程序见解中,我应该开发一个Middleware,它可以拦截每个请求和响应并提取HttpContext,案例Response.Body,然后使用telemetryClient.TrackTrace()将其发送到应用程序分析中。

问题在于,当我调试并提取时,respone的主体始终为空。

这是我的Middleware

public class ResponseBodyInitializer
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly RequestDelegate _next;

    public ResponseBodyInitializer(IHttpContextAccessor httpContextAccessor, RequestDelegate next)
    {
        _httpContextAccessor = httpContextAccessor;
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string resBody = await GetResponseBodyForTelemetry(context);
        SendDataToTelemetryLog(resBody, context);

    }

    private static void SendDataToTelemetryLog(string respBody, HttpContext context)
    {
       if (context.Request.Method == "POST" || context.Request.Method =="PUT")
       {
                var telemetryClient = new TelemetryClient();
                var traceTelemetry = new TraceTelemetry
                {
                    Message = respBody,
                    SeverityLevel = SeverityLevel.Information
                };
                //Send a trace message for display in Diagnostic Search. 
                telemetryClient.TrackTrace(traceTelemetry);
        }
     }

    private async Task<string> GetResponseBodyForTelemetry(HttpContext context)
    {
        var originalBody = context.Response.Body;

        try
        {
            using (var memStream = new MemoryStream())
            {
               context.Response.Body = memStream;

               //await the responsebody
                 await _next(context);
                 if (context.Response.StatusCode == 204)
                 {
                     return null;
                 }

                 memStream.Position = 0;
                 var responseBody = new StreamReader(memStream).ReadToEnd();

                 memStream.Position = 0;
                 await memStream.CopyToAsync(originalBody);

                 return responseBody;
             }
         }
         finally
         {
             context.Response.Body = originalBody;
         }
     }
}

StartUp.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
            _loggerFactory = loggerFactory;
            app.UseDefaultFiles()
                .UseStaticFiles()
                .UseMiddleware<ResponseBodyInitializer>()
                .UseBotFramework();

}

或者还有其他方法可以在app-insights中记录响应吗?

1 个答案:

答案 0 :(得分:0)

这是您必须执行的步骤:-

1)您必须实现ITelemetryInitializer。

2)将IHttpContextAccessor注入到类中,并在Initialize方法中读取响应流。

3)确保传递的ITelemetry对象来自RequestTelemetry类型,并且HttpRequest是Post还是Put。

4)然后,您可以使用IHttpContext.HttpContext.Response.Body属性读取响应,并使用Application Insight将其记录下来。

最后,在Startup.cs的ConfigureService方法中注册您的类

我知道,您不是在实现ITelemetryInitializer,还需要在Initialize方法中读取流

尝试这些步骤,看看是否有帮助。