In ASP.NET Core Razor Pages, how do the @page directive, the Pages folder and OnGet or OnPost methods route a request to code?
answer
- the file path under /Pages is the URL
- Index.cshtml also answers the folder URL
- a template after @page appends; "/" replaces
- On + verb + optional name + Async
- void or Task means Page()
basics
~20 sA .cshtml file under Pages starting with @page is an endpoint whose URL is its path, with Index also answering the folder URL; a template after @page appends segments. The PageModel method named On plus the HTTP verb, such as OnPostAsync, handles it.
solid answer
~40 sWith `AddRazorPages()` and `app.MapRazorPages()`, every `.cshtml` file under `Pages` that starts with `@page` becomes its own endpoint. Its URL is its path below the root: `Pages/Appointments/Book.cshtml` answers `/Appointments/Book`, and an `Index.cshtml` answers its folder URL as well (`/Appointments`). A string after `@page` appends a route template (`@page "{id:int}"` gives `/Appointments/Details/42`), while one starting with `/` or `~/` replaces the path. The page's `@model` class derives from `PageModel` and holds the handlers: public methods named `On` plus an HTTP verb, optionally a handler name and an `Async` suffix, such as `OnGet`, `OnPostAsync` or `OnPostCancelAsync`. Razor Pages picks the one matching the request's verb (a HEAD request falls back to `OnGet`), binds its parameters and runs it; a handler returning `void` or `Task`, or no handler at all, renders the page as if it returned `Page()`.
code
razor · 8 lines@page "{id:int}"
@model DetailsModel
<h1>Appointment @Model.Appointment!.Id</h1>
<p>@Model.Appointment.Patient with @Model.Appointment.Dentist</p>
<p>@Model.Appointment.StartsAt.ToString("f")</p>
<a asp-page="./Index">Back to appointments</a>go deeper
Recall that a file's path under Pages is its URL, that Index answers the folder URL, and that OnGet and OnPost handle the matching verbs.
Explain appended versus overriding @page templates, the handler naming rule with names and Async, and what a handler's return type means.
Diagnose 404s from required route segments, ambiguous-handler exceptions and POSTs that silently render the page because no handler matched.
Shape the folder structure of a large Razor Pages app so URLs, areas and conventions stay stable as features are added and moved.
## Pages are endpoints Razor Pages is the page-focused side of ASP.NET Core MVC. Two calls switch it on, `builder.Services.AddRazorPages()` and `app.MapRazorPages()`, and the `dotnet new webapp` template already has both. From then on, every `.cshtml` file under the **root directory** (`/Pages` by default, `RazorPagesOptions.RootDirectory`) whose first directive is `@page` is a routable page. A `.cshtml` file without `@page`, such as a layout or partial, is not an endpoint. A dentist's practice has these pages: | File | `@page` line | Matches | |---|---|---| | `Pages/Index.cshtml` | `@page` | `/` and `/Index` | | `Pages/Appointments/Index.cshtml` | `@page` | `/Appointments` and `/Appointments/Index` | | `Pages/Appointments/Book.cshtml` | `@page` | `/Appointments/Book` | | `Pages/Appointments/Details.cshtml` | `@page "{id:int}"` | `/Appointments/Details/42` | | `Pages/Appointments/Details.cshtml` | `@page "/visit/{id:int}"` | `/visit/42` only | - The page's URL is its path relative to the root, without `.cshtml`. - An `Index.cshtml` answers both its folder URL and the explicit `/Index` form; links generated to it use the folder URL. - A template after `@page` is **appended** to that path. One starting with `/` or `~/` **overrides** it. - Pages in an area live in `Areas/{area}/Pages/...` and get the area name as their first segment. ## The PageModel The `@model` directive names the page's model, a class that derives from `PageModel` and sits next to the file as `Details.cshtml.cs`: ```csharp public class DetailsModel(IAppointmentService appointments) : PageModel { public Appointment? Appointment { get; private set; } public async Task<IActionResult> OnGetAsync(int id) { Appointment = await appointments.FindAsync(id); return Appointment is null ? NotFound() : Page(); } } ``` - Constructor parameters come from dependency injection, as in a controller. - The base class gives `HttpContext`, `Request`, `User`, `ModelState`, `TempData`, `PageContext` and result helpers such as `Page()`, `RedirectToPage()`, `NotFound()` and `Partial()`. - The view reads public properties through `Model`, so `@Model.Appointment.Patient` renders what the handler loaded. ## Page names Every page also has a **page name**: its path below the root without the extension, such as `/Appointments/Details`. Page names, not URLs, are what the rest of Razor Pages speaks: - `asp-page="/Appointments/Details"` and `RedirectToPage("/Appointments/Details", new { id = 42 })` generate the URL from the page's route, so changing the `@page` template never breaks them; - names without a leading `/` are relative to the current page's folder (`./Details`, `../Index`); - conventions such as `Conventions.AddPageRoute("/Appointments/Index", "bookings")` address pages by name. Because links go through page names and routing, moving `Details.cshtml` to another folder changes one name; hard-coded `/Appointments/Details/42` strings would each need editing. ## How a handler is chosen 1. Handler methods are public instance methods whose names start with `On`: `On` + HTTP verb + optional handler name + optional `Async` suffix. `OnGet`, `OnGetAsync`, `OnPost`, `OnPostAsync`, `OnPostCancelAsync` and `OnDelete` all qualify; `[NonHandler]` excludes a method. 2. The request's HTTP method is matched against the verb, case-insensitively. A `HEAD` request with no `OnHead` falls back to the `GET` handlers. 3. If the request carries a handler name (the `handler` route value or query-string key), a handler with that name wins over the unnamed one. 4. Two candidates that remain equally good, such as `OnPost` and `OnPostAsync` on the same page, make Razor Pages throw `InvalidOperationException` for an ambiguous handler at request time. 5. Handler parameters are model-bound (`OnGetAsync(int id)` reads `id` from the route), then the method runs. ## What a handler returns - `void` or `Task`: the page renders, an implicit `Page()`. - `IActionResult` or `Task<IActionResult>`: whatever result you return, such as `Page()`, `RedirectToPage(...)`, `NotFound()` or `Partial("_Slot", slot)`. - If **no** handler matches the verb, the page still renders. A POST to a page that only has `OnGet` is not rejected with 405; once it passes the page's automatic antiforgery check, it renders the page as for a GET. ## The common mistakes Interviewers probe whether a candidate expects a `Controllers` folder, thinks `Index.cshtml` answers only `/Index`, writes both `OnPost` and `OnPostAsync`, or believes a POST without a handler fails. The model to hold is simple: one file, one route, one PageModel, handlers chosen by verb and name.
- Why does /Appointments/Details without an id return 404 when the page declares @page "{id:int}"?The template after `@page` is appended to the page's path, and `{id:int}` is a required segment, so the route only matches URLs that carry an integer there. Without it, no endpoint matches and routing returns 404 before any handler runs. Writing `{id:int?}` makes the segment optional, and `OnGetAsync(int? id)` then has to handle a missing id.
- What happens if a page declares both OnPost() and OnPostAsync()?Both parse to the same verb with no handler name, so they are equally good candidates for every POST. The handler selector throws `InvalidOperationException` for ambiguous handlers when a POST arrives. The `Async` suffix is only a naming convention; keep one of the two.
- How do you give a page a second URL without moving the file?Add a route through the conventions: `builder.Services.AddRazorPages(o => o.Conventions.AddPageRoute("/Appointments/Index", "bookings"))` keeps `/Appointments` and adds `/bookings`. Changing the `@page` line to start with `/` instead replaces the path-based route rather than adding one.
- Razor Pages need a controller to route requests to each page
- Pages/Appointments/Index.cshtml only answers the URL /Appointments/Index
- @page "{id:int}" replaces the folder path with /{id}
- A POST to a page without OnPost returns 405 Method Not Allowed
- Declaring both OnPost and OnPostAsync lets the async one win