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.