Programmatically Adding the Canonical Tag to Posts in BlogEngine.net

by Chris Tuesday, July 28 2009

On a previous post, I explained how to track bit.ly short URLs on Twitter using Google Analytics through BlogEngine.net (sheesh, what a mouthful).

After doing so, we ran in to the "fun" issue of googlebot crawling and indexing those URLs (ones with the query strings attached). So therefore, we needed a way to add the canonical tag to each page that contained a query string. What we eventually came up with is the following:

 

        string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);

if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;

if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);

HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}

 

It checks if the URL contains "/post/", if true, it checks to see if there are any query strings associated with the URL, if true, it creates the canonical URL and adds the canonical tag to the head of the rendered html page.

However, there is a secondary part to this. The GetApplicationUrl() function was not included, but it basically checks a bunch of variables and concats the full URL.

I posted the full code on the BlogEngine.net Codeplex Discussion Forum. Here is a link to that post.


Tags: , , , ,

ASP.net | Google | Search Engine Optimization (SEO)

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



About this Blog

This is a blog about web design and all things that are related to web design. Pertinent and relevant comments and/or questions are highly encouraged, but please be courteous and thoughtful of others whilest making comments.

If you have benefited from a post, please do the right thing and promote it. You can do this by linking to it, tweeting it, or digging it.

Thank you much.

Recent Comments

Comment RSS