Search code examples
asp.net-coreroutesrazor-pages.net-7.0

How to configure razorpages to not use Index.cshtml as the default page in folders under the Pages folder


To avoid having many files named Index.cshtml in my codebase, I want to use filenames named after the subfolder and with the suffix "Page" as the default pages in a Razor pages site instead of the conventional Index.cshtml.

So instead of having this file structure

/Pages
  /Settings
    Index.cshtml
  /Users
    Index.cshtml

I want this file structure:

/Pages
  /Settings
    SettingsPage.cshtml
  /Users
    UsersPage.cshtml

I have tried setting the route in SettingsPage.cshtml like this:

@page "/"

But this results in this error:

An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches:

/Index
/Settings/SettingsPage

How can I configure the razorpages options/conventions to use what I described above?


Solution

  • Ok, the solution I found was to simply use the folder name in the @page directive like this:

    Instead of having this file /Pages/Settings/Index.cshtml where the first line is

    @page
    

    I have this file /Pages/Settings/SettingsPage.cshtml where the first line is:

    @page "/Settings"
    

    And when linking to the page I need to specify the new page file name instead of Index, for instance, ie. instead of:

    <a class="nav-link text-dark" asp-area="" asp-page="/Settings/Index">Settings</a>
    

    I use

    <a class="nav-link text-dark" asp-area="" asp-page="/Settings/SettingsPage">Settings</a>
    

    This works it seems. Any comments or suggestions are still much appreciated.