How to log outgoing HttpClient request body to Application Insights dependencies table?

Viewed 364

I have a .Net core Web App API which accept request from front-end and then send HTTP POST request to Azure search to get search results.

I just use the build-in application insights logging log basic info in request and dependencies sources with zero logging code.

Now I want to extend the default Application Insights dependencies table to add the request body to Azure search.

What is the easiest way with minimum code?

1 Answers

As per your requirement, you can try the code below:

public class RequestBodyInitializer : ITelemetryInitializer
{
    readonly IHttpContextAccessor httpContextAccessor;

public RequestBodyInitializer(IHttpContextAccessor httpContextAccessor)
{
    this.httpContextAccessor = httpContextAccessor;
}

public void Initialize(ITelemetry telemetry)
{
    if (telemetry is RequestTelemetry requestTelemetry)
    {
        if ((httpContextAccessor.HttpContext.Request.Method == HttpMethods.Post ||
             httpContextAccessor.HttpContext.Request.Method == HttpMethods.Put) &&
            httpContextAccessor.HttpContext.Request.Body.CanRead)
        {
            const string jsonBody = "JsonBody";

            if (requestTelemetry.Properties.ContainsKey(jsonBody))
            {
                return;
            }

            //Allows re-usage of the stream
            httpContextAccessor.HttpContext.Request.EnableRewind();

            var stream = new StreamReader(httpContextAccessor.HttpContext.Request.Body);
            var body = stream.ReadToEnd();

            //Reset the stream so data is not lost
            httpContextAccessor.HttpContext.Request.Body.Position = 0;
            requestTelemetry.Properties.Add(jsonBody, body);
        }
    }
}

and add this to the Startup > ConfigureServices

services.AddSingleton<ITelemetryInitializer, RequestBodyInitializer>();
Related