find a location for property in a new city

Tuesday, 30 March 2010

Add canonical hint to all your web pages in one go

Want to use canonical URLs in all of your web pages for SEO but feeling lazy? Have some ASP.NET/C# code to save doing it yourself for each page.

You will need to paste this into a base page or a master page and then simply call it when needed.
public void InsertCanonical(string canonicalUrl)
{
  //if no url was specified just make the canonical the exact url of this page minus querystring
  //i'm also removing the default.aspx which you most likely wont need to access this page
  if (string.IsNullOrEmpty(canonicalUrl))
  {
    canonicalUrl = "http://" + Request.Url.Host + Request.Url.AbsolutePath.Replace("default.aspx", "");
  }
  //if there is a relative url is provided (i.e. host is NOT provided) add it in plus http protocol
  else if (!canonicalUrl.Contains("www.YOURSITE.com"))
  {
    canonicalUrl = "http://" + Request.Url.Host + canonicalUrl;
  }
  //if the canonical does NOT begin with either http or https protocol add it in
  else if(!Regex.Match(canonicalUrl, "^https?://").Success)
  {
    canonicalUrl = "http://" + canonicalUrl;
  }
  //create the canonical link and add it to the page headers :)
  var link = new HtmlLink();
  link.Href = canonicalUrl.ToLower();
  link.Attributes.Add("rel", "canonical");
  Header.Controls.Add(link);
}

Most times you simply want to use pass null as the parameter just to truncate some ugly tracking querystring paramters off of your URL. So you may appreciate this override too:
public void InsertCanonical()
{
  InsertCanonical(null);
}

Follow britishdev on Twitter

No comments:

Post a Comment