TheDeveloperBlog.com


ASP.NET HtmlLink Example

HtmlLink represents a link element in Web Forms. It can store the <link> canonical tag in an ASP.NET website. We use the HtmlLink control for the canonical link. We look at how the canonical tag is used in ASP.NET.


Intro. First, as a webmaster you should know that the canonical tag, in your HTML head, will tell Google that your Page.aspx file is equal to page.aspx. You can also remove other query strings. This will consolidate Page Rank.

Description: HREF attribute indicates the "best" URL. REL attribute must have the value "canonical".

Example canonical tag in HEAD

<link href="http://example.com/Content/Page.aspx" rel="canonical" />


Add code-behind. Here we add the HtmlLink with the canonical attribute to the page's header. Your ASPX markup file should have runat="server" set on the head. The following code should be in the code-behind C# file, which is called Default.aspx.cs.

Note: You will need to programmatically determine the Href value. This depends on the rest of your code.

Source markup: ASPX

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html>
<head runat="server">
    <title>Example Page</title>
</head>
<body>
</body>
</html>

Code that sets Href: C#

using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
	HtmlLink canonical = new HtmlLink();
	canonical.Href = "http://example.com/Content/Default.aspx";
	canonical.Attributes["rel"] = "canonical";
	Page.Header.Controls.Add(canonical);
    }
}

Resulting markup: HTML

<html>
<head><title>
    Example Page
</title><link href="http://example.com/Content/Page.aspx" rel="canonical" /></head>
<body>
</body>
</html>

Resulting markup for ASPX file. Here we see the final markup in the rendered page that is sent to the client. It contains the new <link> tag in the header. This page could be accessed with and of these urls.

Example URLs

http://www.example.com/Content/page.aspx
http://example.com/Content/Page.aspx
http://example.com/Content/Page.aspx?id=5

Tip: More information on query strings (and the QueryString collection) is available on this site.

QueryString Examples

Summary. We added a canonical link to a web forms page. You can use the HtmlLink element in the code-behind, never manually changing your markup files. Canonical tags in HTML help webmaster SEO tasks.