Search code examples
c#asp.net-corerazor-pages

ASP.NET Core Razor pages routing results in http 404 error


I am using ASP.NET Core Razor pages and have this directive at the top of my Blog.cshtml

@page "/blog/{category?}/page/{pageNo?}"

Now I want these routes all to match to the above:

/blog 

-> It is similar like saying category is null add page by default and pageNo is null

/blog/aspnet 

-> It is like saying category is aspnet add page by default and pageNo is null

/blog/page/1 

-> It is like saying category is null page is there and pageNo is 1

/blog/aspnet/page/1 

-> It is like saying category is aspnet page is there and pageNo is 1

What changes do I have to make?

I tried to make use of AddPageRoute but the below is not working:

// Add services to the container.
builder.Services.AddRazorPages().AddRazorPagesOptions(options => {

    options.Conventions.AddPageRoute("/blog", "blog/{category?}/page/{pageNo?}");    
});

Any help is appreciated. Thank you.


Solution

  • Be sure your Blog page locates in Pages folder(/Pages/Blog.cshtml).

    If you have this directive at the top of Blog.cshtml:

    @page "/blog/{category?}/page/{pageNo?}"
    

    Be sure also make use of AddPageRoute like below:

    builder.Services.AddRazorPages().AddRazorPagesOptions(options => {
        options.Conventions.AddPageRoute("/blog", "blog/{category?}");
        options.Conventions.AddPageRoute("/blog", "blog/{category?}/page");
        options.Conventions.AddPageRoute("/blog", "blog/page/{pageNo?}");  
    });