For software development and maintenance, contact me at or via

How to inject Google Adsense In-Article script into your HTML (ASP.NET Core Razor)

Tue, 24 Dec 2019 by garethbrown

This is how I solved the problem of how to inject a Google Adsense In-Article script within the HTML content of blog articles on a site that I manage.

I wanted the in article text to appear once, half way down the main body of an article. The challenge was to find a reliable and efficient way of where 'half way' in the article HTML was, and then how to inject the Google Adsense In-Article script HTML.

This is a solution for ASP.NET Core Razor. Explanation in the comments with a helper extension method below.

		var entryHtml = entryViewModel.GetHtml();
		// Get count of possible insert locations and if there is a sufficient number,
		// inject ad script
		string paragraphEndStr = "</p>";
		int countParagraphEnds = entryHtml.Split(paragraphEndStr).Length - 1;
		// Only do the insert if we have enough article text (counted by paragraphs)
		if (countParagraphEnds > 2)
			// This is the Adsense script to be inserted, replace this with your own, escaping quotes in the HTML
			string insertHtml = @"
			<div class=""mt-3 mb-3"">
				<script async src=""""></script>
				<ins class=""adsbygoogle""
				style=""display:block; text-align:center;""
				(adsbygoogle = window.adsbygoogle || []).push({});
			// Insert ad script in the middle of content (assuming paragraphs of the same length)
			entryHtml = entryHtml.ReplaceNthOccurance(paragraphEndStr, paragraphEndStr + insertHtml, countParagraphEnds / 2);

ReplaceNthOccurance is an extension method fore replacing a specific occurence of a string in text (in our case, the middle paragraph end tag) that looks like this:

public static string ReplaceNthOccurance(this string obj, string find, string replace, int nthOccurance)
    if (nthOccurance > 0)
        var matchCollection = Regex.Matches(obj, Regex.Escape(find));
        if (matchCollection.Count >= nthOccurance)
            Match match = matchCollection[nthOccurance - 1];
            return obj.Remove(match.Index, match.Length).Insert(match.Index, replace);
    return obj;

Following this, the article text is modified to include the Adsense script, which causes an ad to be rendered in the middle of the article text.

The information provided on this Website is for general informational and educational purposes only. While we strive to provide accurate and up-to-date information, we make no warranties or representations, express or implied, as to the accuracy, completeness, reliability, or suitability of the content, including code samples and product recommendations, presented on this Website.

The use of any information, code samples, or product recommendations on this Website is entirely at your own risk, and we shall not be held liable for any loss or damage, direct or indirect, arising from or in connection with the use of this Website or the information provided herein.
UI block loader
One moment please ...