Razor Pages and handlers
Razor Pages and handlers
Razor Pages organize server-rendered UI by page rather than by controller/action groups. A .cshtml file with @page becomes a page endpoint, and an associated PageModel can handle GET and POST. The template renders the model. This arrangement suits cohesive form-based features, while MVC can suit controller-centered grouping.
AddRazorPages registers services; MapRazorPages exposes page routes. By convention Pages/Request.cshtml maps to /Request. OnGet prepares display state; OnPost handles submission; named handlers such as OnPostSave use handler selection. BindProperty opts a property into model binding, normally for non-GET requests. Validate input on the server using ModelState.IsValid. Return Page() to redisplay invalid input and messages; after a valid state-changing operation, redirect to a GET using RedirectToPage (Post/Redirect/Get, or PRG). Redirect alone does not guarantee idempotency and a query flag is not evidence that data was saved. In our lab no data is saved at all.
Baseline: .NET 10 / C# 14. Examples are independent Web SDK projects, with source files shown below or in the companion fixture. All expected outputs are reasoned, not executed. Run only in an isolated environment with an approved SDK, no real data, no launch profile and no external network. The finite loopback host uses ephemeral data protection keys and a test-only cookie container. No production security configuration is implied.
Trace a GET page handler
Read a query argument and render it as ordinary text. No state changes happen during GET.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddRazorPages();await using var app = builder.Build();app.MapRazorPages();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var response = await client.GetAsync("/Search?term=maps", deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.IsSuccessStatusCode && body.Contains("Search: maps"), "GET handler"); Console.WriteLine("GET handler");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Companion source files (place under the project root exactly as named):
Pages/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersPages/Search.cshtml
@page@model SearchModel<h1>Search: @Model.Term</h1>Pages/Search.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;public sealed class SearchModel : PageModel{ public string Term { get; private set; } = ""; public void OnGet(string? term) => Term = term ?? "";}Expected console observation (unexecuted):
GET handlerThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Redisplay invalid submission
Fetch the page first to obtain the antiforgery cookie and form token. An empty title reaches validation but does not redirect.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddRazorPages();await using var app = builder.Build();app.MapRazorPages();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var formResponse = await client.GetAsync("/Request", deadline.Token); formResponse.EnsureSuccessStatusCode(); var html = await formResponse.Content.ReadAsStringAsync(deadline.Token); // Narrow extraction for this lab's generated form, not a general HTML parser. var input = Regex.Matches(html, "<input\\b[^>]*>", RegexOptions.IgnoreCase) .Cast<Match>().Single(m => m.Value.Contains("name=\"__RequestVerificationToken\"")); var token = WebUtility.HtmlDecode(Regex.Match(input.Value, "value=\"([^\"]+)\"").Groups[1].Value); Check(!string.IsNullOrEmpty(token), "token exists"); using var form = new FormUrlEncodedContent(new Dictionary<string, string> { ["Title"] = "", ["__RequestVerificationToken"] = token }); using var response = await client.PostAsync("/Request", form, deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.StatusCode == HttpStatusCode.OK && body.Contains("Enter a title."), "invalid form redisplayed"); Console.WriteLine("invalid form redisplayed");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Companion source files (place under the project root exactly as named):
Pages/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersPages/Request.cshtml
@page@model RequestModel<!doctype html><html lang="en"><head><title>Request a book</title></head><body><main><h1>Request a book</h1><form method="post"> <div asp-validation-summary="All"></div> <label asp-for="Title"></label> <input asp-for="Title" aria-describedby="title-error" /> <span id="title-error" asp-validation-for="Title"></span> <button type="submit">Request</button></form>@if (Model.Accepted) { <p>Request accepted</p> }</main></body></html>Pages/Request.cshtml.cs
using System.ComponentModel.DataAnnotations;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public sealed class RequestModel : PageModel{ [BindProperty, Required(ErrorMessage = "Enter a title."), StringLength(40)] public string? Title { get; set; } public bool Accepted { get; private set; } public void OnGet(bool accepted = false) => Accepted = accepted; public IActionResult OnPost() { if (!ModelState.IsValid) return Page(); // No persistence in this lab; the redirect is a UI demonstration. return RedirectToPage(new { accepted = true }); }}Expected console observation (unexecuted):
invalid form redisplayedThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Redirect valid submission
With a fresh token and valid title, the response redirects. This demonstrates PRG without claiming persistence.
using System.Net;using System.Text.RegularExpressions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.DataProtection;using Microsoft.AspNetCore.Routing;
// Standalone lab: approved isolated local environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();// Lab-only key ring: avoid persisting antiforgery keys outside the fixture.builder.Services.AddDataProtection().UseEphemeralDataProtectionProvider();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});builder.Services.AddRazorPages();await using var app = builder.Build();app.MapRazorPages();using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() }) { BaseAddress = address }; using var formResponse = await client.GetAsync("/Request", deadline.Token); formResponse.EnsureSuccessStatusCode(); var html = await formResponse.Content.ReadAsStringAsync(deadline.Token); // Narrow extraction for this lab's generated form, not a general HTML parser. var input = Regex.Matches(html, "<input\\b[^>]*>", RegexOptions.IgnoreCase) .Cast<Match>().Single(m => m.Value.Contains("name=\"__RequestVerificationToken\"")); var token = WebUtility.HtmlDecode(Regex.Match(input.Value, "value=\"([^\"]+)\"").Groups[1].Value); Check(!string.IsNullOrEmpty(token), "token exists"); using var form = new FormUrlEncodedContent(new Dictionary<string, string> { ["Title"] = "River Atlas", ["__RequestVerificationToken"] = token }); using var response = await client.PostAsync("/Request", form, deadline.Token); var body = await response.Content.ReadAsStringAsync(deadline.Token); Check(response.StatusCode == HttpStatusCode.Redirect && response.Headers.Location?.OriginalString.Contains("accepted=true", StringComparison.OrdinalIgnoreCase) == true, "POST redirected"); Console.WriteLine("POST redirected"); using var redirected = await client.GetAsync(response.Headers.Location!, deadline.Token); Check((await redirected.Content.ReadAsStringAsync(deadline.Token)).Contains("Request accepted"), "confirmation GET"); Console.WriteLine("confirmation GET");}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}static void Check(bool condition, string name){ if (!condition) throw new InvalidOperationException("Check failed: " + name);}Companion source files (place under the project root exactly as named):
Pages/_ViewImports.cshtml
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpersPages/Request.cshtml
@page@model RequestModel<!doctype html><html lang="en"><head><title>Request a book</title></head><body><main><h1>Request a book</h1><form method="post"> <div asp-validation-summary="All"></div> <label asp-for="Title"></label> <input asp-for="Title" aria-describedby="title-error" /> <span id="title-error" asp-validation-for="Title"></span> <button type="submit">Request</button></form>@if (Model.Accepted) { <p>Request accepted</p> }</main></body></html>Pages/Request.cshtml.cs
using System.ComponentModel.DataAnnotations;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;public sealed class RequestModel : PageModel{ [BindProperty, Required(ErrorMessage = "Enter a title."), StringLength(40)] public string? Title { get; set; } public bool Accepted { get; private set; } public void OnGet(bool accepted = false) => Accepted = accepted; public IActionResult OnPost() { if (!ModelState.IsValid) return Page(); // No persistence in this lab; the redirect is a UI demonstration. return RedirectToPage(new { accepted = true }); }}Expected console observation (unexecuted):
POST redirectedconfirmation GETThe assertion checks the described HTTP contract; a failing check throws rather than printing a success marker.
Common mistakes and limitations
Do not mutate state on GET. Avoid binding full domain entities to forms; explicitly expose allowed input properties. Do not interpret a successful redirect or a query flag as proof of durable persistence. Named handlers are selected by convention; they do not supply authorization by themselves.
Practice and recap
Add a second named POST handler for a preview that validates title but does not save. Explain how the form selects it and what response should be returned for empty input.
Use the fixture assertions to verify the behavior after modification. Explain the observed result before moving to the next lesson.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Razor Pages and handlers — knowledge check
Apply the lesson concepts to the following scenarios.
What turns a Razor file into a page endpoint?
Which handler normally processes GET?
Which result redisplays validation errors?
What does PRG do?
Does BindProperty grant permission to modify a record?