Created
June 12, 2020 05:28
-
-
Save smaglio81/a77c3c7277daa057b9d99fa1954cf4b9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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