View POST request body in Application Insights

前端 未结 9 1584
抹茶落季
抹茶落季 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 17:55

    In Asp.Net core it looks like we dont have to use ITelemetryInitializer. We can use the middleware to log the requests to application insights. Thanks to @IanKemp https://github.com/microsoft/ApplicationInsights-aspnetcore/issues/686

     public async Task Invoke(HttpContext httpContext)
        {
            var requestTelemetry = httpContext.Features.Get();
    
            //Handle Request 
            var request = httpContext.Request;
            if (request?.Body?.CanRead == true)
            {
                request.EnableBuffering();
    
                var bodySize = (int)(request.ContentLength ?? request.Body.Length);
                if (bodySize > 0)
                {
                    request.Body.Position = 0;
    
                    byte[] body;
    
                    using (var ms = new MemoryStream(bodySize))
                    {
                        await request.Body.CopyToAsync(ms);
    
                        body = ms.ToArray();
                    }
    
                    request.Body.Position = 0;
    
                    if (requestTelemetry != null)
                    {
                        var requestBodyString = Encoding.UTF8.GetString(body);
    
                        requestTelemetry.Properties.Add("RequestBody", requestBodyString);
                    }
                }
            }
    
            await _next(httpContext); // calling next middleware
        }
    

提交回复
热议问题