Search code examples
asp.net-corerazorroutes

ASP.NET Core 6 razor page routing default page route within different Areas


In .NET 6 Razor pages, when I use the following code to map page routes while the pages are in the default pages folder or sub-folder of it, it works perfectly like that:

builder.Services.AddRazorPages()
    .AddRazorPagesOptions(options =>
    {       
        options.Conventions.AddPageRoute("/Account/login", "login");
    }
    ).AddRazorRuntimeCompilation(); 

where the page structure is Pages/Account/*.*

However, when I try to map page routes of a page under an area that is not under the default pages folder it does not work as follows:

builder.Services.AddRazorPages()
    .AddRazorPagesOptions(options =>
    {       
        options.Conventions.AddPageRoute("/identity/Account/login", "login");
    }
    ).AddRazorRuntimeCompilation(); 

given that, /identity/Account/login is under the directory /Areas/identity/pages/Account/login and the default Pages folder is pages in the same level as areas folder. i.e. both the areas and main pages folder (pages) are direct children of the main folder.

Notes:

  1. When I access http://localhost/identity/Account/login - it works well
  2. When I add attribute routing in the display template login in the to add - page / it works fine.

Solution

  • For the pages under an areas, you can use the AddAreaPageRoute method to add the page Convention:

    enter image description here

    You can check the following code:

    builder.Services.AddRazorPages().AddRazorPagesOptions(options =>
        {
            options.Conventions.AddPageRoute("/Home/Index", "homeindex");
            options.Conventions.AddAreaPageRoute("Manage","/Admin/AdminIndex", "login");
        }
        );
    

    The result is like this:

    enter image description here

    More detail information, see Razor Pages Routing and Razor Pages route and app conventions in ASP.NET Core.