Razor Pages - Generate link rel canonical


This very website, A Dev Solved It, is an ASP.NET Razor Pages application.

For a given Post page, different URLs work, as long as the first part, with the post id, is the same.

For SEO purposes, I wanted though to set a canonical URL for each post.

I looked around a bit, but I didn't find a simple answer of how to generate a link rel canonical for Razor Pages, most existing results are for ASP.NET MVC.


In my Post.cshtml, I added:

    var scheme = HttpContext.Request.Scheme;
    var host = HttpContext.Request.Host.Value;

    var canonicalUrl = $"{scheme}://{host}/{Model.Post.Id}/{Model.Post.Slug}";

@section Head {
    <link rel="canonical" href="@canonicalUrl" />

, while having a Head section in my _Layout.cshtml:

    @await RenderSectionAsync("Head", required: false)
Author: Dan Dumitru
Last Edit: February 17, 2023
Last Edit February 17, 2023
Created February 11, 2023
Razor Pages

Pay it forward!

Did this solution help you? You can pay it forward and write a solution here yourself, when you have one, helping future Googlers... >> read more

Your Comment

Feel free to post additional info or improvement suggestions.
Optional, never shown, displays gravatar.

Formatting Tips

This editor uses Markdown to easily add code in your posts.

Triple backticks for full line(s) of code (or indent 4 spaces)

let foo = 'bar';

[link text](http://a.com)

*italic* **bold**

More Tips