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)
Dan Dumitru
Last Edit
Feb 17, 2023 at 10:47
Last Edit Feb 17, 2023 at 10:47
Created Feb 11, 2023 at 16:07
Razor Pages

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