Razor Pages
Razor Pages is a page-focused way to build server-rendered web apps. Instead of a controller in one folder and views in another, each page is a pair of files that sit side by side:
Pages/
_ViewImports.cshtml
_ViewStart.cshtml
Shared/_Layout.cshtml
Index.cshtml → /
Contact.cshtml → /Contact
Contact.cshtml.cs (the PageModel class for Contact)
Products/
Index.cshtml → /Products
Edit.cshtml → /Products/EditThe URL comes from the file path — no route table to maintain. Razor Pages is the default for the dotnet new webapp template and is a great fit for form-heavy sites (admin panels, sign-up flows, internal tools).
Turning it on
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseStaticFiles(); // or app.MapStaticAssets() in .NET 9 templates
app.UseRouting();
app.MapRazorPages();
app.Run();A page and its PageModel
The .cshtml file starts with @page, which makes it an endpoint. The PageModel holds the data and the handlers:
// Pages/Contact.cshtml.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class ContactModel(IMessageStore store) : PageModel
{
[BindProperty] // filled from the posted form
public ContactForm Form { get; set; } = new();
public string? Greeting { get; private set; }
public void OnGet() // handles GET /Contact
{
Greeting = "Questions? Drop us a line.";
}
public IActionResult OnPost() // handles POST /Contact
{
if (!ModelState.IsValid)
return Page(); // redisplay with validation messages
store.Save(Form);
TempData["Flash"] = "Thanks, we'll be in touch!";
return RedirectToPage("/Index"); // Post/Redirect/Get
}
}
public class ContactForm
{
[Required] public string Name { get; set; } = "";
[Required, EmailAddress] public string Email { get; set; } = "";
[StringLength(500)] public string? Message { get; set; }
}@* Pages/Contact.cshtml *@
@page
@model ContactModel
<h1>Contact</h1>
<p>@Model.Greeting</p>
<form method="post">
<label asp-for="Form.Name"></label>
<input asp-for="Form.Name" />
<span asp-validation-for="Form.Name"></span>
<label asp-for="Form.Email"></label>
<input asp-for="Form.Email" />
<span asp-validation-for="Form.Email"></span>
<textarea asp-for="Form.Message"></textarea>
<button type="submit">Send</button>
</form>Handlers are found by naming convention:
| Method name | Runs for |
|---|---|
OnGet / OnGetAsync |
GET requests |
OnPost / OnPostAsync |
POST requests |
OnPostDelete |
POST with ?handler=Delete (or asp-page-handler="Delete" on a button) |
OnPut, OnDelete, … |
Other verbs (rare — HTML forms only send GET and POST) |
Razor Pages forms include an anti-forgery token automatically, and posts without a valid token are rejected with 400 Bad Request. That protects users against cross-site request forgery.
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/Contact
$ curl -s -o /dev/null -w "%{http_code}\n" -X POST localhost:5000/Contact -d "Form.Name=Ana"
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/Nope200
400
404
The second request fails with 400 because curl didn't send the anti-forgery token that a real browser form would include.
How handler selection works
The framework looks at the HTTP method plus an optional handler name and picks the matching On<Verb><Handler>[Async] method. Here's that convention implemented with reflection:
using System;
using System.Linq;
using System.Reflection;
var page = new TodoPage();
Dispatch(page, "GET", null);
Dispatch(page, "POST", null);
Dispatch(page, "POST", "Delete");
Dispatch(page, "POST", "Archive");
static void Dispatch(object page, string verb, string handler)
{
string name = "On" + char.ToUpper(verb[0]) + verb.Substring(1).ToLower() + (handler ?? "");
MethodInfo method = page.GetType().GetMethods()
.FirstOrDefault(m => m.Name == name || m.Name == name + "Async");
Console.WriteLine(method == null
? quot;{verb} handler={handler ?? "-"} -> no handler (404)"
: quot;{verb} handler={handler ?? "-"} -> {method.Name}: {method.Invoke(page, null)}");
}
class TodoPage
{
public string OnGet() => "show the list";
public string OnPost() => "add a todo";
public string OnPostDeleteAsync() => "delete a todo";
}GET handler=- -> OnGet: show the list
POST handler=- -> OnPost: add a todo
POST handler=Delete -> OnPostDeleteAsync: delete a todo
POST handler=Archive -> no handler (404)
Route parameters
Add a template after @page to capture parts of the URL:
@page "{id:int}"
@model EditProductModel
<h1>Editing @Model.Product.Name</h1>public class EditProductModel(IProductStore store) : PageModel
{
public Product Product { get; private set; } = default!;
public IActionResult OnGet(int id) // /Products/Edit/7 → id = 7
{
var p = store.Find(id);
if (p is null) return NotFound();
Product = p;
return Page();
}
}Links between pages use the asp-page tag helper so URLs stay correct if you move files: <a asp-page="/Products/Edit" asp-route-id="7">Edit</a> renders <a href="/Products/Edit/7">.
Razor Pages vs MVC
| Razor Pages | MVC | |
|---|---|---|
| Organized by | Page (one URL = one folder location) | Controller (many actions per class) |
| Routing | File path | Attributes or conventional route |
| Logic lives in | PageModel next to the view |
Controller class |
| Best for | Page-centric sites, forms, CRUD screens | Larger apps mixing views and APIs, shared filters |
Both use the same Razor syntax, layouts, tag helpers, model binding and validation — skills transfer directly.
Tip: Always redirect after a successful POST (
RedirectToPage). If you return the page instead, refreshing the browser re-submits the form — the classic "duplicate order" bug.
Test yourself
Which file handles the URL /Products/Edit in a Razor Pages app?
- Controllers/ProductsController.cs
- Views/Products/Edit.cshtml
- Pages/Products/Edit.cshtml
- wwwroot/Products/Edit.html
What does [BindProperty] on a PageModel property do?
- Makes the property read-only
- Fills the property from posted form data during POST requests
- Exposes the property as JSON
- Stores it in the session
Which handler runs for a POST whose form button has asp-page-handler="Delete"?
- OnGetDelete
- OnDelete
- OnPost
- OnPostDelete