Canonical URLs in your ASP.NET MVC2 / MVC3 Application

November 15th, 2010

What are canonical links used for
The Canonical link element was introduced in 2009 to help cleanup duplicate pages on search engines.
The html code is shown below and it basically informs search engines of the primary URL for that page. This means any alternative entry points to that page will not be picked up as duplicate content. This HTML must be specified in the HEAD section of the document.

<link rel="canonical" href="http://example.com/page.html"/>

The search engines have also posted about this on a Google blog post or help center documentation from Google, Yahoo’s blog post, or Microsoft’s blog post.

How to easily use canonical links in MVC2 using Action Filters and Master Pages

Add this to the master page in the head section as follows:

    <%=ViewData["CanonicalURL"] %>
    <!--Your other head info here-->

Create a Filter Attribute (CanonicalURL.cs):

public class CanonicalURL : ActionFilterAttribute
{
    public string Url { get; private set; }
 
    public CanonicalURL(string url)
    {
       Url = url;
    }
 
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        string fullyQualifiedUrl = "http://www.example.com" + this.Url;
        filterContext.Controller.ViewData["CanonicalUrl"] = @"<link rel='canonical' href='" + fullyQualifiedUrl + "' />";
        base.OnResultExecuting(filterContext);
    }
}

Call this from your actions:

[CanonicalURL("Contact-Us")]
public ActionResult Index()
 {
      ContactFormViewModel contact = new ContactFormViewModel(); 
      return View(contact);
}

For some other interesting articles on Search Engine Related posts check out Matt Cutts blog