I’m trying to create SEO friendly URL’s using .NET 6 and Razor Pages (not MVC). From a razor page view:
<a asp-page="/Post" asp-route-id="9">Test Link</a>
I link to a corresponding page handler:
[BindProperty]
public PostViewModel? Post { get; set; }
public async Task<IActionResult> OnGetAsync(int id)
{
Post = new PostViewModel();
Post = await _postService.GetPostAsync(id);
return Page();
}
The page handler will fetch the post by the id
parameter. In the page model PostViewModel
there are properties for Category
, Topic
, and UrlTitle
. I would like to use these properties to generate an SEO friendly URL, like:
https:/wwww.mysite.com/post/{id}/{category}/{topic}/{urltitle}
I’m not sure how to get these property values to the URL?
3
Answers
Try this code:
In a Razor Page View:
Update the
OnGetAsync
method to accept these additional route parameters:And go to the
Configure
method of theStartup
class using theendpoints.MapRazorPages
method:Here, the
pattern
parameter specifies the URL pattern to match, and thedefaults
parameter specifies the default controller and action to use for this route. You will also need to create a correspondingPostController
with anIndex
action to handle the request.At the top of your post page (
.cshtml
file) add:In your home page model (
.cshtml.cs
file) add:and then in your home page create the links using:
Check Route Templates
In Asp.net core Razor page, to set the Friendly URLs, we could override routes template via the
@page
directive in the .cshtml page, like this:Or, we can configure the razor page convention like this:
After that, in the Index page, you can use the following hyperlink to access the Get handler:
For the category, topic or urltitle parameters, if you want to edit them using textbox, you can use JavaScript to build the request url based on the parameters. code like this:
The result as below:
Update
In this scenario, you can modify the Post page code as below:
Post.cshtml page:
Then, the result as below: please pay attention to the url of the hyperlink in the lower-left corner.