Integrating Google Analytics using dependency injection in ASP.NET Core

 
 
  • Gérald Barré

Integrating Google Analytics into your website is straightforward: you copy the tracking snippet into the head tag of your page. However, there is a cleaner alternative. Since ASP.NET Core 2.0, you can use a Tag Helper Component. A Tag Helper Component is a Tag Helper that lets you conditionally modify or add HTML elements from server-side code. This makes it easy to inject content at the end of the head tag or the beginning of the body tag, without touching your Razor layouts directly.

A Tag Helper Component works similarly to a regular Tag Helper, except you must check which tag is currently being processed. For example, to inject code into the head tag, you verify that the current tag name is head.

C#
public class GoogleAnalyticsOptions
{
    public string TrackingCode { get; set; }
}

public class GoogleAnalyticsTagHelperComponent : TagHelperComponent
{
    private readonly GoogleAnalyticsOptions _googleAnalyticsOptions;

    public GoogleAnalyticsTagHelperComponent(IOptions<GoogleAnalyticsOptions> googleAnalyticsOptions)
    {
        _googleAnalyticsOptions = googleAnalyticsOptions.Value;
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        // Inject the code only in the head element
        if (string.Equals(output.TagName, "head", StringComparison.OrdinalIgnoreCase))
        {
            // Get the tracking code from the configuration
            var trackingCode = _googleAnalyticsOptions.TrackingCode;
            if (!string.IsNullOrEmpty(trackingCode))
            {
                // PostContent correspond to the text just before closing tag
                output.PostContent
                    .AppendHtml("<script async src='https://www.googletagmanager.com/gtag/js?id=")
                    .AppendHtml(trackingCode)
                    .AppendHtml("'></script><script>window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}gtag('js',new Date);gtag('config','")
                    .AppendHtml(trackingCode)
                    .AppendHtml("',{displayFeaturesTask:'null'});</script>");
            }
        }
    }
}

You can then register the Tag Helper Component in the Startup class:

C#
public partial class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        // Register the Google Analytics configuration
        services.Configure<GoogleAnalyticsOptions>(options => Configuration.GetSection("GoogleAnalytics").Bind(options));

        // Register the TagHelperComponent
        services.AddTransient<ITagHelperComponent, GoogleAnalyticsTagHelperComponent>();
    }
}

Finally, set the tracking code in the appsettings.json file:

JSON
{
    "GoogleAnalytics": {
        "TrackingCode": "UA-12345678-9"
    }
}

You can verify the script is injected at the end of the head element:

html code generated by the TagHelperhtml code generated by the TagHelper

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

Follow me:
Enjoy this blog?