Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Dependency tracking for outgoing http requests in Application Insights

I have a .NET core API that performs HTTP connections to other API. I am able to visualize the outgoing HTTP request in Application Insights, under Dependency Event Types, but it has only basic information. I'm looking on how to add more information about the outgoing HTTP call (like the HTTP headers for instance).

I've looked into https://learn.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics#trackdependency but I didn't find any concrete way of doing this.

like image 745
kord Avatar asked Oct 27 '25 06:10

kord


1 Answers

As it has been said, the solution proposed by IvanYang is using the recived request instead of the dependency request. I've built this ITelemetryInstance for that:

public void Initialize(ITelemetry telemetry)
{
    var dependecyTelemetry = telemetry as DependencyTelemetry;
    if (dependecyTelemetry == null) return;

    if (dependecyTelemetry.TryGetOperationDetail("HttpRequest", out object request)
        && request is HttpRequestMessage httpRequest)
    {
        foreach (var item in httpRequest.Headers)
        {
            if (!dependecyTelemetry.Properties.ContainsKey(item.Key))
                dependecyTelemetry.Properties.Add(item.Key, string.Join(Environment.NewLine, item.Value));
        }
    }
    if (dependecyTelemetry.TryGetOperationDetail("HttpResponse", out object response)
        && response is HttpResponseMessage httpResponse)
    {
        var responseBody = httpResponse.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        if (!string.IsNullOrEmpty(responseBody))
            dependecyTelemetry.Properties.Add("ResponseBody", responseBody);
    }
}

This will record all the headers sent to the dependency and also the response received

like image 68
Javier Pazos Avatar answered Oct 29 '25 08:10

Javier Pazos