View POST request body in Application Insights

前端 未结 9 1550
抹茶落季
抹茶落季 2020-11-29 17:48

Is it possible to view POST request body in Application Insights?

I can see request details, but not the payload being posted in application insights. Do I have to t

相关标签:
9条回答
  • 2020-11-29 18:11

    I never got @yonisha's answer working so I used a DelegatingHandler instead:

    public class MessageTracingHandler : DelegatingHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Trace the request
            await TraceRequest(request);
    
            // Execute the request
            var response = await base.SendAsync(request, cancellationToken);
    
            // Trace the response
            await TraceResponse(response);
    
            return response;
        }
    
        private async Task TraceRequest(HttpRequestMessage request)
        {
            try
            {
                var requestTelemetry = HttpContext.Current?.GetRequestTelemetry();
    
                var requestTraceInfo = request.Content != null ? await request.Content.ReadAsByteArrayAsync() : null;
    
                var body = requestTraceInfo.ToString();
    
                if (!string.IsNullOrWhiteSpace(body) && requestTelemetry != null)
                {
                    requestTelemetry.Properties.Add("Request Body", body);
                }
            }
            catch (Exception exception)
            {
                // Log exception
            }
        }
    
        private async Task TraceResponse(HttpResponseMessage response)
        {
            try
            {
                var requestTelemetry = HttpContext.Current?.GetRequestTelemetry();
    
                var responseTraceInfo = response.Content != null ? await response.Content.ReadAsByteArrayAsync() : null;
    
                var body = responseTraceInfo.ToString();
    
                if (!string.IsNullOrWhiteSpace(body) && requestTelemetry != null)
                {
                    requestTelemetry.Properties.Add("Response Body", body); 
                }
            }
            catch (Exception exception)
            {
                // Log exception
            }
        }
    }
    

    .GetRequestTelemetry() is an extension method from Microsoft.ApplicationInsights.Web.

    0 讨论(0)
  • 2020-11-29 18:12

    The solution provided by yonisha is clean, but it does not work for me in .Net Core 2.0. This works if you have a JSON body:

    public IActionResult MyAction ([FromBody] PayloadObject payloadObject)
    {
        //create a dictionary to store the json string
        var customDataDict = new Dictionary<string, string>();
    
        //convert the object to a json string
        string activationRequestJson = JsonConvert.SerializeObject(
        new
        {
            payloadObject = payloadObject
        });
    
        customDataDict.Add("body", activationRequestJson);
    
        //Track this event, with the json string, in Application Insights
        telemetryClient.TrackEvent("MyAction", customDataDict);
    
        return Ok();
    }
    
    0 讨论(0)
  • 2020-11-29 18:19

    I am sorry, @yonisha's solution does not seem to work in .NET 4.7. The Application Insights part works OK, but there is actually no simple way to get the request body inside the telemetry initializer in .NET 4.7. .NET 4.7 uses GetBufferlessInputStream() to get the stream, and this stream is "read once". One potential code is like this:

    private static void LogRequestBody(ISupportProperties requestTelemetry)
    {
        var requestStream = HttpContext.Current?.Request?.GetBufferlessInputStream();
    
        if (requestStream?.Length > 0)
            using (var reader = new StreamReader(requestStream))
            {
                string body = reader.ReadToEnd();
                requestTelemetry.Properties["body"] = body.Substring(0, Math.Min(body.Length, 8192));
            }
    }
    

    But the return from GetBufferlessInputStream() is already consumed, and does not support seeking. Therefore, the body will always be an empty string.

    0 讨论(0)
提交回复
热议问题