Razor Pages - multiple routes for same page

problem

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.

solution

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");
});
Gravatar
Author: Dan Dumitru
Last Edit: January 21, 2024
1 Thanks received
Last Edit January 21, 2024
Created January 20, 2024
Views 185
Tags
Razor Pages
ASP.NET

Join in!

I'm building here a library of useful solutions to software development problems.

If you like this project, create an account or add a bookmark, then come back here to write a post yourself when you run into something that might be useful to others...

>> read more

Your Comment

Feel free to post additional info or improvement suggestions.
preview
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