Application Insights - Track HTTP Referer

 
 
  • Gérald Barré

Application Insights is a free service for monitoring web and desktop applications. In a previous post, I showed how to find 404 errors using a custom request. That works well, but it's also useful to know where users came from. By default, the Referer header is not included in telemetry data. Application Insights lets you attach custom data to any event via a Dictionary<string, string>. The goal is to query that data using the following analytic request:

requests
| where resultCode == 404
| project url=url, referer=customDimensions.Referer

There are two places to add extra data: client-side (js) or server-side (c#).

On the client side, you can add data such as the referrer using an object:

JavaScript
appInsights.trackPageView(null, null, { urlReferrer: document.referrer });

That said, I prefer tracking events on the server to avoid losing data due to ad blockers. You can automatically attach custom data to all events by implementing ITelemetryInitializer. Application Insights already ships with several initializers, so you'll find useful examples by browsing the source on GitHub. My initializer is straightforward:

C#
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;

public class RefererTelemetryInitializer : ITelemetryInitializer
{
    private const string HeaderNameDefault = "Referer";

    private readonly IHttpContextAccessor _httpContextAccessor;

    public RefererTelemetryInitializer(IHttpContextAccessor httpContextAccessor)
    {
        if (httpContextAccessor == null) throw new System.ArgumentNullException(nameof(httpContextAccessor));

        _httpContextAccessor = httpContextAccessor;
    }

    public void Initialize(ITelemetry telemetry)
    {
        var context = _httpContextAccessor.HttpContext;
        if (context == null)
            return;

        if (context.Request.Headers.TryGetValue(HeaderNameDefault, out var value))
        {
            telemetry.Context.Properties["Referer"] = value.ToString();
        }
    }
}

Next, register the initializer in the service collection so Application Insights can use it.

C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddSingleton<ITelemetryInitializer, RefererTelemetryInitializer>();

    services.AddMvc();
}

Voilà 😃

As you can see, enriching telemetry data is quick and easy. You can include things like the connected user's tenant ID, the value of a specific header, or any other contextual information relevant to your application.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?