Google Analytics Tag Helper for ASP.NET Core
A simple ASP.NET Core Tag Helper that emits Google Analytics tracking code.

Tag Helpers are a cool new feature in ASP.NET Core that let you define custom HTML elements that are processed server-side.

I thought that it would be neat to be able to emit Google Analytics tracking code by writing a single HTML element:

<google-analytics tracking-id="UA-XXXXXXXX-X" />

I was able to accomplish that with the following tag helper:

public class GoogleAnalyticsTagHelper : TagHelper
{
    public string TrackingId { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.SuppressOutput();

        if (!String.IsNullOrEmpty(TrackingId))
        {
            var sb = new StringBuilder();
            sb.AppendLine($"<script async src=\"https://www.googletagmanager.com/gtag/js?id={TrackingId}\"></script>");
            sb.AppendLine("<script>");
            sb.AppendLine("  window.dataLayer = window.dataLayer || [];");
            sb.AppendLine("  function gtag(){dataLayer.push(arguments);}");
            sb.AppendLine("  gtag('js', new Date());");
            sb.AppendLine($"  gtag('config', '{TrackingId}');");
            sb.AppendLine("</script>");

            output.Content.SetHtmlContent(sb.ToString());
        }
    }
}

I hope this blog post helps you out, or gives you inspiration for your own ASP.NET Core tag helpers.


Posted by Matthew King on 5 November 2017
Permission is granted to use all code snippets under CC BY-SA 3.0 (just like StackOverflow), or the MIT license - your choice!
If you enjoyed this post, and you want to show your appreciation, you can buy me a beverage on Ko-fi or Stripe