Integrating Google Analytics using dependency injection in ASP.NET Core

 
 
  • Gérald Barré

Integrating Google Analytics in your website is not very complicated. You just need to copy the snippet in the head tag of your page. But, there is another way to integrate it. Since ASP.NET Core 2.0, you can create a Tag Helper Component. A Tag Helper Component is a Tag Helper that allows you to conditionally modify or add HTML elements from server-side code. This allows you, for instance, to add some html at the end of the head tag, or the beginning of the body tag.

The code for a Tag Helper Component is almost like a Tag Helper, except you have to check which tag is currently processed. For instance, if you want to inject some code in the head tag, you'll have to check the current tag is actually 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 in the list of services:

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, you have to set the tracking code in the appsettings.json file:

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

You can check the code 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?Buy Me A Coffee💖 Sponsor on GitHub