6

I am using the .net 4.5 framework. I am able to read the request to log in application insights using RequestTelemetry. Written the below code which is working.

var requestTelemetry = telemetry as RequestTelemetry;

if (requestTelemetry == null) return;

var context = HttpContext.Current;
if (context == null) return;   
if (context.Request != null)
{
    if ((context.Request.HttpMethod == HttpMethod.Post.ToString()
        || context.Request.HttpMethod == HttpMethod.Put.ToString()) && WhitelistCheck(context.Request.RawUrl))
    {
        using (var reader = new StreamReader(context.Request.InputStream))
        {
            string requestPayload = reader.ReadToEnd();
            if (!telemetry.Context.Properties.ContainsKey(Request_Payload))
            {
                // TO DO: Don't log Personally identifiable information (PII)
                requestTelemetry.Properties.Add(Request_Payload, requestPayload);
            }
        }
    }
}

To read the response, I am having the issue i e context.Response.OutputStream is write only, we can not read it directly. In core , we have response.body property but not in .net 4.5 framework. Written the below code to log i n application insights which are not working.

using (var reader = new StreamReader(context.Response.OutputStream))
{
    string responseBody = reader.ReadToEnd();
    if (!telemetry.Context.Properties.ContainsKey("Response"))
    {
        requestTelemetry.Properties.Add("Response", responseBody);
    }
}

Please suggest

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Flip side of this question about POST request body https://stackoverflow.com/questions/42686363/view-post-request-body-in-application-insights – Don Cheadle May 15 '19 at 17:17

2 Answers2

0

You are correct that you can not read from the HttpContext.Response in .Net 4.5.

What I would suggest as an alternative is to write the data you want to measure to the HttpContext.Items dictionary and then add that to your telemetry object.

So where you are building your intended your response you would add something like this:

this.HttpContext.Items.Add("customProperty", "Information about the response");

Then you would change the code where you are trying to add the response data to Application Insights.

if (context.Items["customProperty"] != null && !telemetry.Context.Properties.ContainsKey(Request_Payload))
{
    // TO DO: Don't log Personally identifiable information (PII)
    requestTelemetry.Properties.Add(Request_Payload, context.Items["customProperty"].ToString());
}
PerfectlyPanda
  • 3,271
  • 1
  • 6
  • 17
0

I have posted an answer for logging Request/Response body into Application Insights from .NET Framework here Logging Request and response to Application Insight

Short answer - use IHttpModule to intercept the requests/responses and write them into Application Insights.

EladTal
  • 2,167
  • 1
  • 18
  • 10