Google AdSense Tag Helper for ASP.NET Core
A simple ASP.NET Core Tag Helper that emits Google AdSense ad 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 AdSense ad code by writing a single HTML element:

<google-adsense ad-client="ca-pub-XXXXXXXXXXXXXXXX" ad-slot="XXXXXXXXXX" width="300" height="250" />

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

public class GoogleAdsenseTagHelper : TagHelper
{
    public string AdClient { get; set; }
    public string AdSlot { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

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

        if (!String.IsNullOrEmpty(AdClient) && !String.IsNullOrEmpty(AdSlot) && Width > 0 && Height > 0)
        {
            var sb = new StringBuilder();
            sb.AppendLine("<script async src=\"//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js\"></script>");
            sb.AppendLine("<ins class=\"adsbygoogle\"");
            sb.AppendLine($"     style=\"display:inline-block;width:{Width}px;height:{Height}px\"");
            sb.AppendLine($"     data-ad-client=\"{AdClient}\"");
            sb.AppendLine($"     data-ad-slot=\"{AdSlot}\"></ins>");
            sb.AppendLine("<script>");
            sb.AppendLine("(adsbygoogle = window.adsbygoogle || []).push({});");
            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 17 August 2018
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