Search code examples
c#asp.net-core-mvcazure-application-insights

View POST request body in Application Insights


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 track this with some coding?

I am building a MVC core 1.1 Web Api.

POST request


Solution

  • You can simply implement your own Telemetry Initializer:

    For example, below an implementation that extracts the payload and adds it as a custom dimension of the request telemetry:

    public class RequestBodyInitializer : ITelemetryInitializer
    {
        public void Initialize(ITelemetry telemetry)
        {
            var requestTelemetry = telemetry as RequestTelemetry;
            if (requestTelemetry != null && (requestTelemetry.HttpMethod == HttpMethod.Post.ToString() || requestTelemetry.HttpMethod == HttpMethod.Put.ToString()))
            {
                using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
                {
                    string requestBody = reader.ReadToEnd();
                    requestTelemetry.Properties.Add("body", requestBody);
                }
            }
        }
    }
    

    Then add it to the configuration either by configuration file or via code:

    TelemetryConfiguration.Active.TelemetryInitializers.Add(new RequestBodyInitializer());
    

    Then query it in Analytics:

    requests | limit 1 | project customDimensions.body