View POST request body in Application Insights

Dhanuka777 picture Dhanuka777 · Mar 9, 2017 · Viewed 40.7k times · Source

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

Answer

yonisha picture yonisha · Mar 13, 2017

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