Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

ASP.NET HtmlLink Example

This ASP.NET tutorial uses the HtmlLink element in a C# program.

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="" 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" %>
<head runat="server">
    <title>Example Page</title>

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 = "";
	canonical.Attributes["rel"] = "canonical";

Resulting markup: HTML

    Example Page
</title><link href="" rel="canonical" /></head>

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

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.