SkillPilotAI

Razor Pages and forms

Razor Pages is the page-focused way to build server-rendered forms in ASP.NET Core: each page has a .cshtml file and a PageModel class with OnGet/OnPost handlers. Handling a form correctly means binding, server-side validation, Post-Redirect-Get and the antiforgery token.

65.1 Why is it used?

  • In the demo OnPost saves the order and returns the same page (200).
  • Sending the same POST twice creates order #2; pressing refresh in the browser does exactly that.
  • Reason: the last history entry is the POST, and refresh resends it with the form data.
  • Fix: after success send a redirect instead of a page: Post-Redirect-Get.
C#
public class CheckoutModel(OrderStore orders)    : PageModel{    [BindProperty]    public OrderInput Input { get; set; } = new();    public string? Message { get; set; }     public void OnGet() { }     public void OnPost()    {        var order = orders.Add(Input);        Message = $"Order #{order.Id} placed";    }}
Output
$ curl -i -b jar.txt localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=110001" \  -d "__RequestVerificationToken=$TOKEN"HTTP/1.1 200 OK<h1>Checkout</h1><p>Order #1 placed</p> $ curl -i -b jar.txt localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=110001" \  -d "__RequestVerificationToken=$TOKEN"HTTP/1.1 200 OK<h1>Checkout</h1><p>Order #2 placed</p>

65.2 Setup: dotnet new webapp

  • AddRazorPages registers services; MapRazorPages routes every page by its file path.
  • AddDistributedMemoryCache + AddSession + UseSession enable session (used later).
C#
var builder = WebApplication.CreateBuilder(args);builder.Services.AddRazorPages();builder.Services.AddSingleton<OrderStore>();builder.Services.AddDistributedMemoryCache();builder.Services.AddSession(o =>    o.IdleTimeout = TimeSpan.FromMinutes(20)); var app = builder.Build();app.MapStaticAssets();app.UseSession(); app.MapRazorPages()   .WithStaticAssets(); app.Run();
Output
$ dotnet new webapp -n ShopThe template "ASP.NET Core Web App (Razor Pages)"was created successfully.Restore succeeded. $ dotnet run --no-launch-profile --urls http://localhost:5065info: Microsoft.Hosting.Lifetime[14]      Now listening on: http://localhost:5065info: Microsoft.Hosting.Lifetime[0]      Application started. Press Ctrl+C to shut down.

65.3 PageModel, BindProperty and validation

  • Pages/Checkout.cshtml.cs lives in Pages, so its URL is /Checkout.
  • The class inherits PageModel; OrderStore comes from DI through the constructor.
  • [BindProperty] binds the POSTed form fields into Input automatically.
  • OnGet handles GET, OnPost handles POST.
  • Validation rules are attributes on OrderInput: [Required], [StringLength(40)], [RegularExpression] for a 6-digit pincode.
  • On render the rules also become data-val-* attributes so the browser can check them first.
C#
public class OrderInput{    [Required, StringLength(40)]    public string Name { get; set; } = "";     [Required]    [RegularExpression(@"^\d{6}$",        ErrorMessage = "Pincode must be 6 digits")]    public string Pincode { get; set; } = "";}
Output
$ curl -s localhost:5065/Checkout | grep Pincode<input type="text" data-val="true"  data-val-regex="Pincode must be 6 digits"  data-val-regex-pattern="^\d{6}$"  data-val-required="The Pincode field is required."  id="Input_Pincode" name="Input.Pincode" value="" />

65.4 Razor Page: form and tag helpers

  • @page makes the file a routable page; no separate controller is needed.
  • asp-for="Input.Name" gives the input the name Input.Name so BindProperty recognises it.
  • asp-validation-for is the slot for the error message.
  • The form tag helper adds the hidden __RequestVerificationToken automatically.
HTML
@page@model CheckoutModel@{ ViewData["Title"] = "Checkout"; } <h1>Checkout</h1><form method="post">    <input asp-for="Input.Name" />    <span asp-validation-for="Input.Name"></span>    <input asp-for="Input.Pincode" />    <span asp-validation-for="Input.Pincode"></span>    <button>Place order</button></form>@section Scripts {    <partial name="_ValidationScriptsPartial" />}
Output
$ curl -s localhost:5065/Checkout<form method="post">    <input type="text" … id="Input_Name"      maxlength="40" name="Input.Name" value="" />    <span class="field-validation-valid"      data-valmsg-for="Input.Name" …></span>    …<input name="__RequestVerificationToken"  type="hidden" value="CfDJ8GLxwzfG0FhPo9K…" /></form>

65.5 OnPost with RedirectToPage

  • OnPost returns IActionResult.
  • If ModelState.IsValid is false, return Page(): the form shows again with errors and the typed values.
  • On success save the order and RedirectToPage("Thanks", new { id }).
  • The response is 302; the browser GETs /Thanks/1, so a refresh only repeats this GET.
C#
public IActionResult OnPost(){    if (!ModelState.IsValid)        return Page();     var order = orders.Add(Input);    return RedirectToPage("Thanks",        new { id = order.Id });}
Output
$ curl -i -b jar.txt -c jar.txt localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=110001" \  -d "__RequestVerificationToken=$TOKEN"HTTP/1.1 302 FoundLocation: /Thanks/1 $ curl -b jar.txt localhost:5065/Thanks/1    <title>Thanks - Shop</title><h1>Thank you, Asha!</h1><p>Order #1 will reach 110001.</p>
Post-Redirect-Get (PRG)
  1. 1.Browser POSTs /Checkout with form data + antiforgery token

  2. 2.Server validates (ModelState.IsValid) and saves the order

  3. 3.Server returns 302 Found, Location: /Thanks/1 (not a page)

  4. 4.Browser GETs /Thanks/1 and shows "Thank you, Asha!"

  5. 5.Refresh repeats only this safe GET: no duplicate order

Without PRG the last history entry is the POST, so refresh sends it again

Checkpoint: with Pincode "12ab", Page() is returned and the Name field still shows Asha, because BindProperty already filled Input and asp-for renders that value. The error appears under the pincode.

Output
$ curl -i -b jar.txt -c jar.txt localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=12ab" \  -d "__RequestVerificationToken=$TOKEN"HTTP/1.1 200 OK    <input … name="Input.Name" value="Asha" />    <span class="field-validation-error" …>      Pincode must be 6 digits</span>

65.6 Antiforgery token (CSRF)

  • CSRF: another site makes your browser submit a form with your cookies.
  • Razor Pages checks an antiforgery token on every POST, on by default.
  • POST without the token: 400 Bad Request. GET gives the cookie + hidden token; POST with both: 302.
Terminal
# 1. POST without tokencurl -i localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=110001" # 2. GET: antiforgery cookie + hidden tokencurl -i -c jar.txt localhost:5065/Checkout # 3. POST with cookie + tokencurl -i -b jar.txt -c jar.txt \  localhost:5065/Checkout \  -d "Input.Name=Asha&Input.Pincode=110001" \  -d "__RequestVerificationToken=$TOKEN"
Output
$ curl -i localhost:5065/Checkout -d "…"HTTP/1.1 400 Bad RequestContent-Length: 0 $ curl -i -c jar.txt localhost:5065/CheckoutHTTP/1.1 200 OKSet-Cookie: .AspNetCore.Antiforgery.sznpiabFdBo=CfDJ8…;  path=/; samesite=strict; httponly<input name="__RequestVerificationToken"  type="hidden" value="CfDJ8GLxwzfG0FhPo9K…" /> $ curl -i -b jar.txt -c jar.txt … -d "…"HTTP/1.1 302 FoundLocation: /Thanks/1
How the antiforgery token stops CSRF
  1. 1.GET /Checkout: server sets the antiforgery cookie and puts a hidden __RequestVerificationToken in the form

  2. 2.User submits: browser sends the cookie + the hidden token

  3. 3.Server checks that the token matches the cookie: 302, order placed

  4. 4.Evil site auto-submits a form: the browser sends the cookie but the site cannot read the token

  5. 5.No valid token: 400 Bad Request

65.7 Session and named handlers

  • Session remembers one user's data across requests; the data stays on the server, the browser has only a session id cookie.
  • SetString after the order is saved, GetString in OnGet to prefill the name.
  • A page can have several POST actions: asp-page-handler="Forget" adds ?handler=Forget and calls OnPostForget.
  • OnPostForget removes the name from session and redirects; the field comes back empty.
C#
public void OnGet(){    Input.Name = HttpContext.Session        .GetString("Customer") ?? "";} // in OnPost, after the order is savedHttpContext.Session.SetString(    "Customer", Input.Name);
Output
$ curl -i -b jar.txt -c jar.txt … -d "…"HTTP/1.1 302 FoundLocation: /Thanks/1Set-Cookie: .AspNetCore.Session=CfDJ8GLxwzfG0FhPo9K…;  path=/; samesite=lax; httponly $ curl -s -b jar.txt localhost:5065/Checkout | grep Input.Name    <input type="text" … id="Input_Name"      maxlength="40" name="Input.Name" value="Asha" />
C#
// Checkout.cshtml:// <form method="post"//       asp-page-handler="Forget"> public IActionResult OnPostForget(){    HttpContext.Session.Remove("Customer");    return RedirectToPage();}
Output
$ curl -s -b jar.txt localhost:5065/Checkout | grep Forget<form method="post" action="/Checkout?handler=Forget"> $ curl -i -b jar.txt -c jar.txt \  "localhost:5065/Checkout?handler=Forget" -d "…"HTTP/1.1 302 FoundLocation: /Checkout$ curl -s -b jar.txt localhost:5065/Checkout | grep Input.Name    <input … name="Input.Name" value="" />
StoreWhere the data livesLifetime
TempDataCookieUntil it is read once
SessionServer (distributed cache); browser holds only the session id cookieUntil the idle timeout (20 min here)
[BindProperty] InputCurrent requestOne request

65.8 Comparison: MVC vs Razor Pages

PointMVCRazor Pages
Unit of codeController with many actions + separate viewsOne page = .cshtml + PageModel (.cshtml.cs)
RoutingRoute pattern {controller}/{action}/{id?}File path under Pages (Pages/Checkout -> /Checkout)
HandlersAction methods, [HttpGet]/[HttpPost]OnGet, OnPost, named OnPostForget
Form bindingAction parameters / model[BindProperty] on the PageModel
Good forLarger apps, APIs + views togetherPage-focused apps, forms, CRUD screens

65.9 Common mistakes

  • Returning a page after a successful POST: refresh creates a duplicate.
  • Turning antiforgery off with [IgnoreAntiforgeryToken] to fix a 400: any site's form can then place an order. Send the token instead (RequestVerificationToken header for fetch).
  • Trusting client-side validation only: curl or Postman bypass it; always check ModelState.IsValid on the server.
  • Putting [BindProperty] on the entity itself instead of a separate input class with only the form fields (over-posting).
  • Large data in session, or in-memory session on multiple servers: use a distributed cache like Redis.
C#
// Wrong: CSRF protection completely off[IgnoreAntiforgeryToken]public class CheckoutModel(OrderStore orders)    : PageModel// curl -i localhost:5065/Checkout -d "…"// no token, no cookie:// HTTP/1.1 302 Found// Location: /Thanks/1 // Right: keep protection on, send the tokenpublic class CheckoutModel(OrderStore orders)    : PageModel// <form method="post"> adds the token// curl without token: HTTP/1.1 400 Bad Request// fetch(): send the token in the//   RequestVerificationToken header

65.10 Interview tips

  • PageModel OnGet/OnPost handle requests; [BindProperty] binds the form into an input model.
  • In OnPost: invalid ModelState -> return Page(); success -> RedirectToPage (Post-Redirect-Get).
  • The antiforgery token protects against CSRF and is on by default.
  • Client validation is for UX only; server validation is mandatory.
  • TempData lives until read once, session until the idle timeout.