Skip to content

Instantly share code, notes, and snippets.

@smaglio81
Created June 12, 2020 05:28
Show Gist options
  • Save smaglio81/a77c3c7277daa057b9d99fa1954cf4b9 to your computer and use it in GitHub Desktop.
Save smaglio81/a77c3c7277daa057b9d99fa1954cf4b9 to your computer and use it in GitHub Desktop.
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;
namespace YourNamespace
{
// https://stackoverflow.com/questions/42686363/view-post-request-body-in-application-insights
public class TrackRequestBodyInitializer : ITelemetryInitializer
{
private readonly IHttpContextAccessor httpContextAccessor;
public TrackRequestBodyInitializer(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public void Initialize(ITelemetry telemetry)
{
if (telemetry is RequestTelemetry requestTelemetry)
{
var context = httpContextAccessor.HttpContext;
var request = context.Request;
if (request.CanReadBody())
{
const string jsonBody = TrackConstants.JsonBody;
if (!context.Items.ContainsKey(jsonBody))
{
return;
}
if (requestTelemetry.Properties.ContainsKey(jsonBody))
{
return;
}
var body = context.Items[jsonBody] as string;
requestTelemetry.Properties.Add(jsonBody, body);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment