Razor Pages - multiple routes for same page


In my ASP.NET Razor Pages project I have for my Post entity an Edit page in the Pages folder named PostEdit.cshtml.

I want to get to it using the URL "/posts/edit/{id?}", so I have at the top of the page:

@page "/posts/edit/{id?}"

To avoid code duplication, I want to use the same page also for adding a new Post, having a different route presented to the user, "/posts/add".

But I cannot add multiple routes to a single Razor page, adding a second @page directive gives an error.


After a lot of googling and trying different things I was able to use a feature that seems to be named Friendly Routes, using AddPageRoute from Conventions when setting up the Razor Pages in the Startup.cs or the Program.cs file.

services.AddRazorPages(options =>
    options.Conventions.AddPageRoute("/PostEdit", "/posts/add");
Dan Dumitru
Last Edit
Jan 21, 2024 at 10:24
Last Edit Jan 21, 2024 at 10:24
Created Jan 20, 2024 at 12:24
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