Is it possible to catch request/response bodies and add them into a telemetry initializer? or is this doable at all? I have been trying the below approach with no success, this is for a web application in .framework 4.6.1 after reading a bit about it, I found that NET 4.6.1 uses GetBufferlessInputStream() to get the stream, and this stream is "read once" so, by the time the code hits this initializer GetBufferlessInputStream() is already consumed and therefore the body is an empty string, I have seen other solutions but they are all for MVC .NET CORE and suggest to add code in the controller and right now it is not an option for me.
Edit for more context: this is a "rest-ish" based wcf webapp hosted in IIS that uses .net framework 4.6.1, we have a sepparated Monitoring project that implements App insights which is distributed as an internal nuget package for several projects, and here is where I would like to implement a new telemetry intializer (if possible) that would allow me to catch request bodies
Thank you all for you help.
public void Initialize(ITelemetry telemetry)
{
try
{
var requestTelemetry = telemetry as RequestTelemetry;
if (requestTelemetry != null && (HttpContext.Current.Request.HttpMethod == HttpMethod.Post.ToString() || HttpContext.Current.Request.HttpMethod == HttpMethod.Put.ToString()))
{
using (var reader = new StreamReader(HttpContext.Current.Request.GetBufferlessInputStream()))
{
string requestBody = reader.ReadToEnd();
requestTelemetry.Properties.Add("requestBody", requestBody);
}
}
}
catch (Exception ex)
{
Logger.Error($"Error initializing telemetry.{Environment.NewLine}{ex}");
}
}