Add a Cannonical link to your web page AND handle RouteData

I have a site (https://anchoredmarriage.com) that uses RouteData for the articles. I want to add a dynamics canonical link to the pages and still handle the route data. 

In other words, most pages would have

<link href="https://anchoredmarriage.com/Default.aspx" rel="canonical">

But the pages with RouteData would look like this

<link href="https://anchoredmarriage.com/article/Wedding_Decorations" rel="canonical">

 

Dim link As HtmlLink = New HtmlLink()
 
'if your site is not using routedata, this is all you need
Dim strPage As String = String.Format("https://anchoredmarriage.com/{0}", Path.GetFileName(Page.AppRelativeVirtualPath))
 
'get the routedata
Dim strLink As String = Convert.ToString(Page.RouteData.Values("ArticleLink"))
 
'this code handles routedata
Select Case strLink
    Case ""
    Case Else
        strPage = String.Format("https://anchoredmarriage.com/article/{0}", strLink)
End Select
 
link.Attributes("href") = strPage
link.Attributes("rel") = "canonical"
Page.Header.Controls.Add(link)

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences