Razor Pages
Page model, handlers and file-based routing.
Razor Pages in ASP.NET Core
Category: ASP.NET Core Fundamentals
Difficulty: Intermediate
Target framework: .NET 9+
Previous topic: MVC Pattern
Next topic: Continue with the next topic in your ASP.NET Core Fundamentals roadmap
1. About
Understand Razor Pages, Page Models, handler methods, and file-based routing with practical ASP.NET Core examples.
Prerequisites
- Basic C# and object-oriented programming
- HTTP request and response fundamentals
- Dependency injection
- Basic Razor syntax and ASP.NET Core middleware
- Familiarity with the MVC pattern
Learning outcomes
By the end of this module, you will be able to:
- Explain Razor Pages and when they are a good fit.
- Understand the relationship between a
.cshtmlpage and itsPageModel. - Use
OnGet,OnPost, and named handler methods. - Understand file-based routing, route templates, and route parameters.
- Bind and validate form input safely.
- Use dependency injection and application services from a Page Model.
- Build secure, maintainable Razor Pages applications.
- Compare Razor Pages with MVC controllers and Minimal APIs.
2. Introduction
What are Razor Pages?
Razor Pages is a page-focused programming model in ASP.NET Core for building server-rendered web applications. Each page typically combines a Razor .cshtml file for the UI with a C# PageModel class that handles page requests.
In MVC, developers often organize related requests around controllers and actions. Razor Pages organizes the application around individual pages and their handlers.
A page might contain:
Index.cshtml— the Razor markup shown to the user.Index.cshtml.cs— the Page Model that handles requests and supplies data.
For example:
Pages/
└── Products/
├── Index.cshtml
└── Index.cshtml.cs
The /Products URL is commonly associated with Pages/Products/Index.cshtml, because Index is the default page name within that folder.
Why does Razor Pages exist?
For page-oriented applications, a controller/action structure can sometimes add indirection: developers navigate from a URL to a controller, then an action, then a view in another folder. Razor Pages puts the UI and its page-handling code close together.
Razor Pages helps with:
- Form-heavy websites.
- Admin pages and dashboards.
- Account, profile, and settings pages.
- CRUD interfaces.
- Applications where each page has a clear set of actions.
| Need | How Razor Pages helps |
|---|---|
| Keep a page's code close to its UI | .cshtml and .cshtml.cs are colocated |
| Handle GET and POST requests | Page handler methods |
| Build routes from a folder structure | File-based routing |
| Validate form input | Model binding, validation attributes, and ModelState |
| Reuse application logic | Inject services into the Page Model |
| Render server-side HTML | Razor templates |
Key idea: Razor Pages is not a replacement for Razor syntax. Razor is the templating syntax; Razor Pages is an ASP.NET Core web programming model built around pages and handlers.
3. Real-life analogy: A bank service counter
Imagine a bank with separate service counters for deposits, address changes, and statement requests.
- Each counter represents a page focused on one user task.
- The counter's visible form and instructions resemble the
.cshtmlfile. - The employee handling the request resembles the Page Model.
- Different request types—asking for information or submitting a form—resemble GET and POST handlers.
- The bank's shared account system resembles injected application services.
A customer asking for a statement and a customer submitting an address change use different handlers even if both actions belong to a related service area.
The analogy helps explain why Razor Pages keeps a page's UI and request-handling code together while still allowing shared business logic to live in services.
4. Architecture diagram
The page route is discovered from the Pages folder and any configured route template. The selected handler runs, obtains the data needed by the page, and returns a page result or another response.
5. Concept explanation
5.1 What is a Razor Page?
A Razor Page is usually made of two files:
| File | Responsibility |
|---|---|
Index.cshtml | Contains Razor markup and presentation |
Index.cshtml.cs | Contains the Page Model and request handlers |
Example:
Pages/Hello.cshtml:
@page
@model HelloModel
<h1>Hello, Razor Pages!</h1>
<p>@Model.Message</p>
Pages/Hello.cshtml.cs:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesDemo.Pages;
public sealed class HelloModel : PageModel
{
public string Message { get; private set; } = string.Empty;
public void OnGet()
{
Message = "This value came from the Page Model.";
}
}
The @page directive makes the file an addressable Razor Page endpoint. The @model directive declares the Page Model type used by the view.
5.2 What is a Page Model?
A Page Model is a C# class—commonly derived from PageModel—that contains page-related request-handling logic and the data the Razor page needs.
It can:
- Define handler methods such as
OnGetandOnPost. - Receive route and form values through model binding.
- Validate input.
- Call application services through dependency injection.
- Set properties that the Razor markup displays.
- Return results such as
Page(),RedirectToPage(),NotFound(), orBadRequest().
A Page Model should not become a dumping ground for every business rule. For maintainability, delegate substantial use cases to services or domain components.
5.3 What are handler methods?
Handlers are methods that Razor Pages selects for a request. The HTTP method and, optionally, a handler name determine which handler is eligible.
Common handlers include:
| Handler | Typical purpose |
|---|---|
OnGet() | Handle a GET request |
OnPost() | Handle a POST request |
OnGetAsync() | Asynchronous GET handling |
OnPostAsync() | Asynchronous POST handling |
OnPostDeleteAsync() | Named POST handler called Delete |
OnPostSaveAsync() | Named POST handler called Save |
A handler may return void, Task, IActionResult, Task<IActionResult>, or supported result types depending on the intended response and framework conventions. For most handlers that need to return different responses, IActionResult or Task<IActionResult> is a useful choice.
Example:
public IActionResult OnGet()
{
return Page();
}
Page() tells Razor Pages to render the current page.
5.4 How named handlers work
A single page may have multiple actions. Named handlers allow those actions to be distinguished without creating a separate route for each.
Pages/Products/Manage.cshtml:
@page
@model RazorPagesDemo.Pages.Products.ManageModel
<h1>Manage product</h1>
<form method="post" asp-page-handler="Save">
<button type="submit">Save</button>
</form>
<form method="post" asp-page-handler="Delete">
<button type="submit">Delete</button>
</form>
Pages/Products/Manage.cshtml.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesDemo.Pages.Products;
public sealed class ManageModel : PageModel
{
public void OnGet()
{
}
public IActionResult OnPostSave()
{
// Call a service to save changes in a real application.
return RedirectToPage();
}
public IActionResult OnPostDelete()
{
// Authorize and delete through a service in a real application.
return RedirectToPage();
}
}
The asp-page-handler tag helper generates the appropriate handler route value for the form. A POST to the Save handler selects OnPostSave; a POST to the Delete handler selects OnPostDelete.
Security warning: A button being visible only to an administrator is not sufficient protection. The handler must enforce authorization and validate the operation on the server.
5.5 File-based routing
Razor Pages uses the file system under the Pages root as the basis for route discovery.
Example structure:
Pages/
├── Index.cshtml
├── About.cshtml
└── Products/
├── Index.cshtml
├── Details.cshtml
└── Edit.cshtml
Common conventional routes:
| Page file | Typical URL |
|---|---|
Pages/Index.cshtml | / |
Pages/About.cshtml | /About |
Pages/Products/Index.cshtml | /Products |
Pages/Products/Details.cshtml | /Products/Details |
These are conventional examples; explicit route templates, route conventions, areas, and application configuration can change the resulting URLs.
5.6 Route parameters
A route can contain parameters that are bound to Page Model properties or handler parameters.
Pages/Products/Details.cshtml:
@page "{id:int}"
@model RazorPagesDemo.Pages.Products.DetailsModel
<h1>Product details</h1>
<p>Product ID: @Model.Id</p>
Pages/Products/Details.cshtml.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesDemo.Pages.Products;
public sealed class DetailsModel : PageModel
{
public int Id { get; private set; }
public IActionResult OnGet(int id)
{
Id = id;
// A real application should retrieve the product by ID
// and return NotFound() when it does not exist.
return Page();
}
}
The route template "{id:int}" indicates that the URL contains an integer route parameter. A request such as /Products/Details/12 can bind 12 to id.
Route constraints help select matching routes; they do not replace validation, existence checks, or authorization.
5.7 Model binding and [BindProperty]
Model binding takes values from the request and assigns them to handler parameters or properties.
A Page Model can use [BindProperty] to bind a property, typically for form submissions:
[BindProperty]
public CreateProductInput Input { get; set; } = new();
By default, property binding is generally intended for non-GET requests. SupportsGet = true can enable binding on GET requests when needed:
[BindProperty(SupportsGet = true)]
public string? SearchTerm { get; set; }
Use GET binding for appropriate query/filter values, not for sensitive or state-changing operations. Prefer narrow input models over binding an entire database entity.
5.8 Validation
Razor Pages supports data annotations and ModelState, much like MVC.
using System.ComponentModel.DataAnnotations;
namespace RazorPagesDemo.Models;
public sealed class CreateProductInput
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;
[Range(typeof(decimal), "0.01", "1000000")]
public decimal Price { get; set; }
}
In a POST handler, check ModelState.IsValid before calling a service to persist data.
if (!ModelState.IsValid)
{
return Page();
}
The page can display errors with validation tag helpers. Client-side validation helps users correct input quickly, but server-side validation is still required.
5.9 Dependency injection
Page Models support constructor injection.
public sealed class IndexModel : PageModel
{
private readonly IProductService _products;
public IndexModel(IProductService products)
{
_products = products;
}
}
Register the service in Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
This keeps the Page Model focused on HTTP and page behavior while the service handles the application use case.
5.10 Page(), redirects, and other results
| Result | Purpose | Example |
|---|---|---|
Page() | Render the current page | return Page(); |
RedirectToPage() | Redirect to a Razor Page | return RedirectToPage("/Products/Index"); |
NotFound() | Return HTTP 404 | return NotFound(); |
BadRequest() | Return HTTP 400 | return BadRequest(); |
Forbid() | Indicate the user is authenticated but not permitted, subject to auth configuration | return Forbid(); |
Challenge() | Initiate an authentication challenge, subject to auth configuration | return Challenge(); |
RedirectToPage("Details", new { id }) | Redirect with route values | return RedirectToPage("Details", new { id }); |
Select results that reflect the actual operation and security context. A redirect is often appropriate after a successful form submission; returning Page() is useful when displaying validation errors.
5.11 Razor Pages and MVC can coexist
An ASP.NET Core application can register MVC controllers and Razor Pages together. Use Razor Pages for page-focused workflows and controllers where controller/action organization or API conventions suit the endpoint better.
This is a design choice rather than a requirement to migrate every endpoint to one model.
6. Important terminology
| Term | Meaning | Example |
|---|---|---|
| Razor Pages | Page-focused ASP.NET Core programming model | Product edit page |
| Razor | Syntax for combining HTML and C# | @Model.Name |
@page | Makes a .cshtml file an addressable Razor Page | @page "{id:int}" |
| Page Model | C# class that handles a page's requests | EditModel |
| Handler | Method selected for a page request | OnPostAsync() |
| Named handler | Handler selected using a name | OnPostDelete() |
| File-based routing | Routes discovered from files under Pages | Pages/Products/Index.cshtml |
| Route parameter | Value captured from a URL | {id:int} |
| Model binding | Converts request values to .NET values | Form field to Input.Name |
BindProperty | Enables property model binding | [BindProperty] |
ModelState | Holds model-binding and validation state | ModelState.IsValid |
| Tag helper | Server-side helper that enhances HTML elements | asp-page-handler |
| PRG | Post/Redirect/Get flow after a successful POST | RedirectToPage() |
7. How it works internally
A typical Razor Pages request follows these steps:
- The browser sends an HTTP request.
- ASP.NET Core middleware processes the request.
- Endpoint routing matches a Razor Pages endpoint based on the file-derived route and configured conventions.
- The framework creates the Page Model and resolves its dependencies through DI.
- Model binding reads route, query, and form values into parameters or bound properties.
- Validation runs and errors are recorded in
ModelState. - Razor Pages selects a handler such as
OnGet,OnPost, or a named handler. - The handler executes and may call an application service.
- The handler returns a result, such as
Page(), a redirect, or an error response. - If the result renders the page, Razor executes the
.cshtmltemplate using the Page Model. - ASP.NET Core sends the resulting HTTP response to the browser.
This is a conceptual sequence. Exact framework stages vary, and handlers that return redirects or other non-page results may not render the Razor page.
8. Syntax explained
The @page directive
@page
Declares that the file is an addressable Razor Page. A route template can be supplied:
@page "{id:int}"
This adds an integer route parameter called id.
The @model directive
@model RazorPagesDemo.Pages.Products.DetailsModel
Declares the Page Model type used by the page. It makes the model's public members available through Model in Razor markup.
Handler naming
public void OnGet() { }
public Task<IActionResult> OnPostAsync() { ... }
public IActionResult OnPostDelete() { ... }
OnGet: handler for GET.OnPost: handler for POST.Async: conventional suffix for an asynchronous method; it is not itself what makes the method asynchronous.Delete: named handler suffix, typically selected by a handler route value such as?handler=Deleteor generated byasp-page-handler="Delete".
The [BindProperty] attribute
[BindProperty]
public CreateProductInput Input { get; set; } = new();
Asks the framework to bind request values to the property under the applicable binding rules. Use narrow input types and validate values before processing them.
The asp-page-handler tag helper
<button type="submit" asp-page-handler="Save">Save</button>
Generates a link or form target that selects the named handler. For a form POST, the matching handler is commonly OnPostSave or OnPostSaveAsync.
9. Code examples
The following examples target .NET 9+ and use standard ASP.NET Core Razor Pages conventions.
9.1 Simple example: Display a message
Pages/Welcome.cshtml:
@page
@model RazorPagesDemo.Pages.WelcomeModel
<h1>Welcome</h1>
<p>@Model.Message</p>
Pages/Welcome.cshtml.cs:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace RazorPagesDemo.Pages;
public sealed class WelcomeModel : PageModel
{
public string Message { get; private set; } = string.Empty;
public void OnGet()
{
Message = "Welcome to Razor Pages in ASP.NET Core.";
}
}
Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Browse to /Welcome to see the message. In a complete application, configure authentication if needed and add all required middleware and error pages.
9.2 Intermediate example: A validated form with GET and POST handlers
Models/CreateProductInput.cs:
using System.ComponentModel.DataAnnotations;
namespace RazorPagesDemo.Models;
public sealed class CreateProductInput
{
[Required]
[StringLength(100, MinimumLength = 2)]
public string Name { get; set; } = string.Empty;
[Range(typeof(decimal), "0.01", "1000000")]
public decimal Price { get; set; }
}
Pages/Products/Create.cshtml.cs:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesDemo.Models;
namespace RazorPagesDemo.Pages.Products;
public sealed class CreateModel : PageModel
{
[BindProperty]
public CreateProductInput Input { get; set; } = new();
[TempData]
public string? Message { get; set; }
public void OnGet()
{
// Prepare any page data required for the initial GET.
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
// Re-render the form with validation messages.
return Page();
}
// Demo only. Persist through an application service in a real project.
Message = $"'{Input.Name}' passed validation.";
// Post/Redirect/Get avoids resubmitting this POST on refresh.
return RedirectToPage();
}
}
Pages/Products/Create.cshtml:
@page
@model RazorPagesDemo.Pages.Products.CreateModel
<h1>Create product</h1>
@if (!string.IsNullOrWhiteSpace(Model.Message))
{
<p role="status">@Model.Message</p>
}
<form method="post">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Input.Name"></label>
<input asp-for="Input.Name" />
<span asp-validation-for="Input.Name"></span>
<label asp-for="Input.Price"></label>
<input asp-for="Input.Price" />
<span asp-validation-for="Input.Price"></span>
<button type="submit">Create</button>
</form>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
The Razor Pages form tag helper supports anti-forgery protection for typical form posts. Keep server-side validation even when client-side validation scripts are enabled.
Production note: This example does not save a product. In a real application, inject a service, enforce authorization and business rules, persist valid input, and handle expected errors. Do not accept price or privileged fields blindly from a form.
9.3 Production example: Page Model + service + EF Core
This example shows how a page can use a service to retrieve data without putting database queries directly in the Page Model.
Entity
Data/ProductEntity.cs:
namespace RazorPagesDemo.Data;
public sealed class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
DbContext
Data/AppDbContext.cs:
using Microsoft.EntityFrameworkCore;
namespace RazorPagesDemo.Data;
public sealed class AppDbContext(DbContextOptions<AppDbContext> options)
: DbContext(options)
{
public DbSet<ProductEntity> Products => Set<ProductEntity>();
}
ViewModel
Models/ProductListItemViewModel.cs:
namespace RazorPagesDemo.Models;
public sealed class ProductListItemViewModel
{
public int Id { get; init; }
public string Name { get; init; } = string.Empty;
public decimal Price { get; init; }
}
Service contract
Services/IProductService.cs:
using RazorPagesDemo.Models;
namespace RazorPagesDemo.Services;
public interface IProductService
{
Task<IReadOnlyList<ProductListItemViewModel>> GetProductsAsync(
CancellationToken cancellationToken);
}
Service implementation
Services/ProductService.cs:
using Microsoft.EntityFrameworkCore;
using RazorPagesDemo.Data;
using RazorPagesDemo.Models;
namespace RazorPagesDemo.Services;
public sealed class ProductService(AppDbContext db) : IProductService
{
public async Task<IReadOnlyList<ProductListItemViewModel>> GetProductsAsync(
CancellationToken cancellationToken)
{
// Select only the fields needed by the page.
return await db.Products
.AsNoTracking()
.OrderBy(p => p.Name)
.Select(p => new ProductListItemViewModel
{
Id = p.Id,
Name = p.Name,
Price = p.Price
})
.ToListAsync(cancellationToken);
}
}
Page Model
Pages/Products/Index.cshtml.cs:
using Microsoft.AspNetCore.Mvc.RazorPages;
using RazorPagesDemo.Models;
using RazorPagesDemo.Services;
namespace RazorPagesDemo.Pages.Products;
public sealed class IndexModel(IProductService products) : PageModel
{
public IReadOnlyList<ProductListItemViewModel> Products { get; private set; }
= Array.Empty<ProductListItemViewModel>();
public async Task OnGetAsync(CancellationToken cancellationToken)
{
Products = await products.GetProductsAsync(cancellationToken);
}
}
Razor page
Pages/Products/Index.cshtml:
@page
@model RazorPagesDemo.Pages.Products.IndexModel
<h1>Products</h1>
@if (Model.Products.Count == 0)
{
<p>No products are available.</p>
}
else
{
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model.Products)
{
<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
</tr>
}
</tbody>
</table>
}
Program.cs
using Microsoft.EntityFrameworkCore;
using RazorPagesDemo.Data;
using RazorPagesDemo.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
Configure DefaultConnection using user secrets locally or secure deployment configuration. Do not commit production credentials. Create and apply EF Core migrations as part of database setup.
Why this design is useful:
- The Page Model handles page-specific request behavior.
- The service encapsulates the retrieval use case.
- EF Core performs asynchronous I/O.
- Projection limits returned data to what the page needs.
AsNoTracking()avoids change-tracking overhead for this read-only query.- Cancellation can propagate to the database query.
A production catalog will usually also need pagination, resource authorization where applicable, monitoring, and robust error handling.
10. Recommended folder structure
RazorPagesDemo/
├── Data/
│ ├── AppDbContext.cs
│ └── ProductEntity.cs
├── Models/
│ ├── CreateProductInput.cs
│ └── ProductListItemViewModel.cs
├── Services/
│ ├── IProductService.cs
│ └── ProductService.cs
├── Pages/
│ ├── Index.cshtml
│ ├── Index.cshtml.cs
│ ├── Error.cshtml
│ ├── Error.cshtml.cs
│ ├── Products/
│ │ ├── Index.cshtml
│ │ ├── Index.cshtml.cs
│ │ ├── Create.cshtml
│ │ ├── Create.cshtml.cs
│ │ ├── Details.cshtml
│ │ └── Details.cshtml.cs
│ ├── Shared/
│ │ └── _Layout.cshtml
│ ├── _ViewImports.cshtml
│ └── _ViewStart.cshtml
├── wwwroot/
│ ├── css/
│ └── js/
├── appsettings.json
└── Program.cs
Keep each page's .cshtml and .cshtml.cs files together. Shared application logic belongs in services or domain components, not duplicated across multiple Page Models.
11. Execution flow: line by line
Consider this Page Model handler:
public async Task OnGetAsync(CancellationToken cancellationToken)
{
Products = await products.GetProductsAsync(cancellationToken);
}
- A browser sends a GET request to the product listing URL.
- Middleware processes the request.
- Routing selects the Razor Pages endpoint associated with
Pages/Products/Index.cshtml. - ASP.NET Core creates
IndexModeland injectsIProductService. - The framework selects
OnGetAsyncfor the GET request. - The handler passes the request cancellation token to the service.
- The service executes an asynchronous EF Core query.
- The query returns a list of ViewModels.
- The handler assigns the list to
Products. - The page result is produced through the normal Razor Pages handler conventions.
- Razor evaluates
Model.Productsand renders the table. - The resulting HTML is sent to the browser.
The Page Model does not need to call Page() explicitly in this example because the handler returns void-like asynchronous completion (Task), and Razor Pages renders the current page by default. If the handler needs to choose between rendering, redirecting, or returning an error, use an action-result return type.
12. Real project usage
| Industry | Example | How Razor Pages can help |
|---|---|---|
| E-commerce | Product edit and inventory pages | Forms, validation, and page-specific handlers |
| Banking | Profile and statement-request pages | Separate page workflows with authorization and careful data handling |
| Healthcare | Appointment booking pages | Bind and validate scheduling input before invoking services |
| Logistics | Shipment detail pages | Route parameters identify a shipment, and the Page Model retrieves its data |
| Social media | Account settings pages | Page-specific form handling and validation |
| Enterprise software | Admin dashboards and CRUD pages | File-based organization for many page workflows |
The suitability depends on application architecture. Large applications can combine Razor Pages with MVC controllers and APIs where each model is a better fit.
13. Performance considerations
Memory
- Avoid loading entire tables for a page.
- Use pagination for large lists.
- Pass only the data required by the Razor page.
- Avoid storing request-specific state in singleton services.
CPU
- Keep complex calculations out of Razor markup.
- Avoid repeated transformations in the view.
- Profile slow handlers before optimizing.
- Cache expensive, safe-to-cache results when invalidation is clear.
Scalability
- Use asynchronous I/O for database and network calls.
- Propagate cancellation tokens to supported downstream operations.
- Avoid
.Resultand.Wait()in request-handling code. - Keep shared state in appropriate shared stores rather than process-local memory when the application scales horizontally.
Optimization
- Use projection to select only required columns.
- Inspect database query plans and add indexes based on actual usage.
- Paginate or filter large collections.
- Configure HTTP caching for suitable static or public content.
- Measure request latency, database duration, error rates, and memory.
Note:
asynchelps release the request thread while asynchronous I/O is waiting; it does not automatically speed up CPU-bound work.
14. Security considerations
Overposting
Binding an entire entity from a form can allow unwanted fields to be modified.
Defense: Use a narrow input model and explicitly map permitted values.
Cross-site request forgery (CSRF)
Cookie-authenticated applications can be vulnerable to forged state-changing requests.
Defense: Use anti-forgery protection for applicable form submissions. Standard Razor Pages form helpers support generating tokens, and the framework validates them under the usual configuration. Do not disable this protection without a clear, reviewed reason.
Broken access control
A route such as /Orders/123 must not let every signed-in user read order 123.
Defense: Authorize access to the specific resource in the handler or service, not merely the page route. Do not rely on hidden buttons or unpredictable IDs.
Cross-site scripting (XSS)
Untrusted text can become executable content if rendered unsafely.
Defense: Use Razor's normal output encoding. Avoid Html.Raw for untrusted input and apply context-appropriate encoding or sanitization.
SQL injection
Building SQL by concatenating untrusted values can alter query meaning.
Defense: Prefer EF Core LINQ or parameterized SQL.
Sensitive data exposure
Error pages, logs, or UI models can reveal secrets or personal information.
Defense: Keep secrets in secure configuration, use generic production error pages, log safely, and expose only fields needed by the page.
Additional security practices
- Enforce HTTPS.
- Authenticate users and authorize protected operations.
- Validate input on the server.
- Use least-privilege database credentials.
- Avoid logging passwords, tokens, or sensitive payloads.
- Keep dependencies patched.
- Validate uploaded files if uploads are supported.
15. Ten common mistakes
| # | Mistake | Why it happens | How to fix it |
|---|---|---|---|
| 1 | Forgetting @page | The file looks like an ordinary Razor template | Add @page when the file should be a Razor Pages endpoint |
| 2 | Putting all business logic in the Page Model | It is the easiest place to start | Delegate substantial use cases to services/domain components |
| 3 | Using the wrong handler name | Handler naming conventions are unfamiliar | Match HTTP method and suffix, such as OnPostSave |
| 4 | Binding an entire database entity | It reduces initial coding | Use a narrow input model |
| 5 | Forgetting ModelState.IsValid | Developers assume annotations save data safely | Validate before processing a typical form POST |
| 6 | Assuming client-side validation is enough | Invalid browser input seems blocked | Validate on the server every time |
| 7 | Skipping resource authorization | The URL contains a valid ID | Authorize the current user against the requested resource |
| 8 | Returning Page() after a successful POST without considering duplicates | The form is easy to re-submit | Use Post/Redirect/Get where appropriate |
| 9 | Loading all rows for a listing | Small test data hides query cost | Filter, project, and paginate |
| 10 | Putting queries in .cshtml | The view is where the data is displayed | Retrieve data in a service and expose it through the Page Model |
16. Production best practices
- Keep Page Models focused. They should coordinate page behavior, not own every business rule.
- Use dependency injection. Inject services rather than constructing concrete dependencies manually.
- Separate UI input models from entities. Limit what untrusted requests can change.
- Validate server-side. Browser validation is only a usability aid.
- Check
ModelStatebefore processing input. Return the page with validation errors when appropriate. - Use asynchronous I/O. Prefer asynchronous EF Core methods for database operations.
- Propagate cancellation tokens. Let supported downstream operations observe request cancellation.
- Protect form posts. Retain anti-forgery defenses for applicable cookie-authenticated requests.
- Authorize each resource operation. A valid route ID does not imply permission.
- Use Post/Redirect/Get. Redirect after successful form submissions when appropriate.
- Use narrow input models. Do not bind sensitive entity fields directly from a form.
- Use EF Core projection. Return only data needed by the page.
- Use
AsNoTracking()for read-only queries when appropriate. Choose tracking when entity changes need to be persisted through the context. - Paginate large results. Bound database work, memory use, and response size.
- Keep Razor markup presentational. Avoid database access and complex workflows in
.cshtml. - Use safe output handling. Retain Razor's default encoding and avoid unsafe raw HTML.
- Centralize exception handling. Avoid exposing stack traces in production.
- Log useful events. Use structured logs without secrets or sensitive form contents.
- Keep secrets out of source control. Use user secrets locally and secure deployment configuration.
- Test important flows. Cover handler behavior, validation, authorization, persistence, and routing.
- Use route templates intentionally. Keep URLs consistent and avoid confusing route constraints with authorization.
- Use tag helpers consistently. They help generate links, forms, and validation markup that respect configured routes.
- Choose service lifetimes deliberately. Do not capture scoped dependencies in singletons.
- Measure before optimizing. Profile handler latency and database queries before adding caches.
- Use accessible HTML. Associate labels with inputs and make validation feedback understandable.
- Organize around features. Keep each page's markup and Page Model together and shared logic in appropriate services.
- Keep authentication and authorization explicit. Page handlers should not assume the user has permission just because the page loaded.
- Avoid stateful assumptions. Requests can be served by different application instances.
- Return appropriate results. Distinguish validation errors, missing resources, forbidden access, and successful operations.
- Document non-obvious conventions. Custom route conventions and named handlers should be discoverable to teammates.
17. Interview questions
Beginner questions
1. What are Razor Pages?
Razor Pages is a page-focused ASP.NET Core programming model for building web UI. A page usually contains a .cshtml file and an associated Page Model that handles requests.
2. What is a Page Model?
A Page Model is the C# class associated with a Razor Page. It exposes data for the UI and contains handlers for requests. It can also receive dependencies through constructor injection.
3. What does @page do?
The @page directive makes a .cshtml file an addressable Razor Pages endpoint. It can also include a route template.
4. What does @model do?
It declares the Page Model type used by the Razor page. The view accesses the model through the Model expression.
5. What is OnGet() used for?
It handles a GET request for the page. It commonly prepares data for display.
6. What is OnPost() used for?
It handles a POST request, often from a form submission. It typically validates input and calls an application service.
7. How does file-based routing work?
Razor Pages discovers page endpoints from files under the Pages directory and derives routes from their paths, subject to route templates and conventions.
8. What does Page() return?
It returns a result that renders the current Razor Page.
9. What is [BindProperty]?
It asks the framework to bind request values to a Page Model property under the applicable model-binding rules. GET binding generally requires SupportsGet = true.
10. Can Razor Pages use dependency injection?
Yes. A Page Model can receive services through its constructor, just like controllers and other ASP.NET Core components.
Intermediate questions
11. What is the difference between Razor Pages and MVC?
Razor Pages organizes request handling around pages and page handlers. MVC typically organizes requests around controllers and actions, with views commonly in separate folders. Both use ASP.NET Core infrastructure and can coexist.
12. What is a named handler?
A named handler is a handler distinguished by a suffix, such as OnPostDelete. It can be selected using a handler route value, often generated by asp-page-handler.
13. How does model binding work in Razor Pages?
The framework reads supported route, query, and form values and assigns them to handler parameters or bound properties. Validation then records applicable errors in ModelState.
14. How should validation errors be handled?
Check ModelState.IsValid in the handler before processing a typical form submission. If invalid, return Page() so the form can display the errors.
15. Why use a separate input model?
A dedicated input model limits accepted fields, provides clear validation rules, and reduces the risk of overposting sensitive entity properties.
16. How do you redirect to another Razor Page?
Use RedirectToPage(), optionally specifying a page path and route values, such as RedirectToPage("/Products/Details", new { id }).
17. Can Razor Pages have route parameters?
Yes. A route template such as @page "{id:int}" defines a route parameter that can be bound to a handler parameter or model property.
18. Why use Post/Redirect/Get?
After a successful POST, redirecting to a GET reduces accidental form resubmission when the resulting page is refreshed. It does not replace idempotency protections for sensitive or duplicate operations.
19. How do Razor Pages use services?
Register a service in DI and inject it into the Page Model. The handler calls the service, then prepares the result for the page or returns another response.
20. Can Razor Pages return a 404?
Yes. A handler can return NotFound() when a requested resource does not exist or should not be exposed as found.
Advanced questions
21. When would you choose Razor Pages over MVC?
Choose Razor Pages when the application is naturally page-oriented and colocating UI and handlers improves discoverability. MVC can be preferable when controller/action organization better fits the route and workflow design. There is no universal winner.
22. Can Razor Pages and MVC be used in the same application?
Yes. Register Razor Pages and controller endpoints as needed. This lets page-focused UI coexist with controller-based workflows or APIs.
23. How would you prevent overposting in Razor Pages?
Use a purpose-built input model with only allowed fields, validate it, authorize the operation, and explicitly map permitted values to the domain or persistence object.
24. How would you authorize access to /Orders/123?
Authenticate the user, identify the requested order, and perform resource-level authorization. Do not assume that knowing the order ID grants access.
25. What is the difference between a route constraint and validation?
A route constraint helps determine whether a URL matches an endpoint, such as requiring an integer ID. Validation checks the meaning and acceptability of bound input. Neither replaces authorization.
26. How would you improve a slow Razor Pages listing?
Measure request and query latency, use projection, inspect database query plans, add justified indexes, paginate results, use asynchronous I/O, and cache only when freshness and access rules permit.
27. Should a Page Model contain business logic?
It can contain simple page coordination, but substantial business rules should generally be delegated to domain or application services. This improves reuse and testability.
28. How do anti-forgery tokens help?
They help protect applicable cookie-authenticated form submissions against cross-site request forgery. Razor Pages form helpers support token generation, and the framework validates tokens under the usual configuration.
29. What is the role of SupportsGet?
[BindProperty(SupportsGet = true)] enables binding a property from GET request data. This is useful for filters and search terms, but it should not be used to perform state-changing operations through GET.
30. How do you test a Razor Pages application?
Unit-test service and domain behavior. Use integration tests to verify page routes, handler behavior, model binding, validation, authorization, persistence, redirects, and HTTP status codes.
18. Hands-on exercise
Exercise: Build a product search page
Goal: Create a Razor Page that accepts a search term and displays matching products.
Requirements
- Create
Pages/Products/Search.cshtmland its Page Model. - Add a
SearchTermproperty that can bind from a GET request. - Create a product service with a search method.
- Display the matching products in the page.
- Handle an empty search term gracefully.
- Use asynchronous service calls.
- Add a details page with an integer route parameter.
- Return
NotFound()for missing products. - Add tests for empty, matching, and non-matching searches.
- As an extension, implement the search with EF Core and pagination.
Acceptance criteria
/Products/Search?searchTerm=keyboardshows matching products.- Search terms are displayed safely.
- The page handles no results without throwing an exception.
- The Page Model calls a service rather than querying the database directly.
- Large result sets are paginated in the extension.
- Server-side rules are enforced.
19. Mini project: Product management portal
Project goal
Build a small product-management portal using Razor Pages, EF Core, and an application service.
Features
- Product list and details pages
- Search and pagination
- Create and edit forms
- Input validation and clear error messages
- EF Core persistence
- Named handlers where multiple operations on a page make sense
- Authentication and authorization for administrative operations
- Anti-forgery protection
- Structured logging and centralized error handling
- Automated tests
Suggested milestones
| Milestone | Deliverable |
|---|---|
| 1. Page structure | List, details, and create pages |
| 2. Read workflows | Retrieve products through a service |
| 3. Write workflows | Create/edit with validated input models |
| 4. Persistence | EF Core context and migrations |
| 5. Security | Authentication, authorization, anti-forgery protection |
| 6. Quality | Logging, exception handling, integration tests |
| 7. Performance | Search, pagination, query review |
Definition of done
A permitted user can list, view, create, and edit products; invalid input is handled gracefully; protected operations enforce authorization; and the key workflows have automated tests.
20. Quiz: 10 multiple-choice questions
Question 1
What does @page do?
A. Registers a database table
B. Makes a .cshtml file an addressable Razor Page endpoint
C. Adds a CSS file
D. Creates a controller
Correct answer: B
Explanation: The @page directive enables the file to participate as a Razor Pages endpoint.
Question 2
Which method typically handles a GET request?
A. OnDelete()
B. OnSave()
C. OnGet()
D. OnUpdate()
Correct answer: C
Explanation: OnGet is the conventional GET handler name.
Question 3
Which method is a conventional POST handler?
A. OnPost()
B. OnRead()
C. OnRoute()
D. OnView()
Correct answer: A
Explanation: OnPost handles a POST request when selected by Razor Pages.
Question 4
What is a Page Model?
A. A database migration
B. A CSS template
C. An HTTP proxy
D. The C# class associated with a Razor Page
Correct answer: D
Explanation: The Page Model supplies page data and handles requests through handler methods.
Question 5
Which directive declares the Page Model type in a .cshtml file?
A. @usingmodel
B. @model
C. @injectmodel
D. @class
Correct answer: B
Explanation: @model declares the model type used by the Razor template.
Question 6
What does @page "{id:int}" describe?
A. A CSS selector
B. A database column
C. A route containing an integer-constrained parameter
D. A service lifetime
Correct answer: C
Explanation: The template defines a route parameter named id with an integer route constraint.
Question 7
What should a typical form handler do when ModelState.IsValid is false?
A. Ignore the errors
B. Save the data anyway
C. Delete the form
D. Return the page with validation errors
Correct answer: D
Explanation: Returning the page lets the user correct invalid input. Server-side validation is still required.
Question 8
How is a named POST handler such as OnPostDelete commonly selected?
A. By adding asp-page-handler="Delete" to the form or submit control
B. By renaming the database
C. By changing the CSS class
D. By disabling routing
Correct answer: A
Explanation: The handler name is supplied through a handler route value, often generated by the tag helper.
Question 9
What is a good defense against overposting?
A. Hide fields using CSS
B. Bind a narrow input model and map allowed fields
C. Trust all incoming properties
D. Disable validation
Correct answer: B
Explanation: A dedicated input model restricts which fields the request is allowed to supply.
Question 10
Can Razor Pages and MVC controllers coexist?
A. No, only one can be registered
B. Only in development
C. Yes, when the application registers the needed endpoints
D. Only if neither uses dependency injection
Correct answer: C
Explanation: ASP.NET Core applications can use both programming models in one application.
21. Summary
One-minute revision
Razor Pages is a page-focused ASP.NET Core model. A .cshtml file contains UI markup, while its Page Model handles requests through methods such as OnGet and OnPost. Routes are commonly derived from files under Pages, and route templates can define parameters. Model binding, validation, DI, and application services support maintainable page workflows.
Five-minute revision
@pagemakes a file an addressable Razor Page.@modeldeclares the Page Model type.- File-based routing maps page files to URLs.
OnGetcommonly handles GET requests;OnPosthandles POST requests.- Named handlers distinguish operations such as Save and Delete.
- Model binding reads request data into parameters or bound properties.
- Validation errors are available through
ModelState. - Use a narrow input model for form submissions.
- Inject services into Page Models and keep business rules out of presentation code.
- Protect state-changing requests and authorize each protected resource operation.
- Use asynchronous I/O, projection, and pagination for efficient data access.
- Razor Pages can coexist with MVC controllers and APIs.
Bullet-point summary
- Razor Pages organizes web UI around pages.
- A page usually has
.cshtmland.cshtml.csfiles. @pageenables endpoint routing for the page.- Handler names conventionally reflect HTTP methods.
- Named handlers allow multiple operations on a page.
- File-based routes can be customized.
- Model binding and validation work with Page Models.
- Dependency injection supports service-based design.
- Security checks must run on the server.
- Use the model that best fits the application's organization.
Memory tricks
- Page = UI + Page Model: the page's markup and request logic live near each other.
- GET = Get/display; POST = Process submission: a useful convention, not an authorization rule.
- File path → route: a page's location under
Pageshelps determine its URL. - Bind → Validate → Handle → Respond: a simplified mental model for a page request.
Flashcards
| Front | Back |
|---|---|
What does @page do? | Makes the file an addressable Razor Page |
| What is a Page Model? | C# class for page data and handlers |
| Which handler commonly handles GET? | OnGet() |
| Which handler commonly handles POST? | OnPost() |
| How are named handlers selected? | With a handler route value such as asp-page-handler |
What does [BindProperty] do? | Enables binding request data to a property |
What does ModelState.IsValid check? | Whether binding/validation errors were recorded |
| Why use an input model? | To validate input and limit bindable fields |
22. Cheat sheet
| Need | Razor Pages solution |
|---|---|
| Create an addressable page | Add @page to a .cshtml file under Pages |
| Declare its Page Model | Use @model Namespace.PageModelType |
| Handle GET | OnGet() / OnGetAsync() |
| Handle POST | OnPost() / OnPostAsync() |
| Handle a named operation | OnPostSave() / asp-page-handler="Save" |
| Bind a form model | [BindProperty] |
| Bind a GET filter property | [BindProperty(SupportsGet = true)] |
| Check validation | ModelState.IsValid |
| Render current page | Page() |
| Redirect to a page | RedirectToPage(...) |
| Return 404 | NotFound() |
| Inject a service | Constructor injection |
| Register Razor Pages | builder.Services.AddRazorPages() |
| Map Razor Pages | app.MapRazorPages() |
| Protect form posts | Anti-forgery tokens and validation |
| Improve large listings | Filter, project, paginate |
Minimal setup
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
This is a minimal illustration. A real production app should configure appropriate exception handling, authentication, authorization, and other required middleware for its needs.
23. Comparison table
Razor Pages vs MVC vs Minimal APIs
| Aspect | Razor Pages | MVC | Minimal APIs |
|---|---|---|---|
| Main organization | Pages and handlers | Controllers and actions | Route handlers |
| Typical use | Page-focused server-rendered UI | Controller/action workflows and views | Lightweight HTTP endpoints and APIs |
| UI template | Razor .cshtml page | Razor view | Not required |
| Route discovery | Commonly file-based | Conventional or attribute routing | Endpoint route definitions |
| Request logic | Page Model handlers | Controller actions | Delegates/handler methods |
| DI support | Yes | Yes | Yes |
| Best fit | Forms and page-oriented tasks | Related actions organized around controllers | API endpoints and concise HTTP handlers |
Razor Pages vs MVC view organization
| Aspect | Razor Pages | MVC |
|---|---|---|
| UI and handler location | Usually colocated under Pages | Controller and view commonly live in separate folders |
| Request entry point | Page handler | Controller action |
| Route convention | File-based, customizable | Conventional and/or attribute routing |
| Named operations | Named page handlers | Separate controller actions |
| Shared infrastructure | ASP.NET Core middleware, DI, validation, authorization | ASP.NET Core middleware, DI, validation, authorization |
Neither model is universally better. Choose the one that makes the application's request and UI organization easiest to maintain.
24. Key takeaways
- Razor Pages is a page-focused ASP.NET Core programming model.
.cshtmlcontains the UI; the Page Model contains page-specific request handling.@pagemakes a file an addressable endpoint.OnGetandOnPostare conventional handlers for GET and POST.- Named handlers let one page support distinct operations.
- File-based routing is conventional and can be customized.
- Model binding and validation simplify form processing but do not replace business rules.
- Input models reduce overposting risk.
- Inject services and keep substantial business logic outside Page Models.
- Apply authentication, authorization, anti-forgery protection, and safe output handling.
- Use asynchronous I/O, projection, and pagination where appropriate.
- Razor Pages and MVC can coexist in one application.
25. Revision checklist
- I can explain Razor Pages and when to choose it.
- I understand the difference between Razor syntax and Razor Pages.
- I can create a
.cshtmlpage and Page Model. - I know what
@pageand@modeldo. - I can implement
OnGetandOnPost. - I can use a named handler.
- I understand file-based routing and route parameters.
- I can bind and validate form input.
- I know how to inject a service into a Page Model.
- I can return a page, redirect, or 404.
- I can explain common Razor Pages security risks.
- I can compare Razor Pages with MVC and Minimal APIs.
26. Further reading
Continue with these related topics on the Logic Lense / .NET Interview Ready roadmap:
- ASP.NET Core Fundamentals roadmap
- MVC Pattern (previous topic)
- Routing in ASP.NET Core
- Model Binding and Validation
- Dependency Injection
- Middleware in ASP.NET Core
- Configuration and
appsettings.json - Service Lifetimes
- Filters in ASP.NET Core
- Authentication and Authorization
- Entity Framework Core
- REST API fundamentals
Last updated 10/23/2026
Your notes
Sign in to save personal notes on this topic — they'll sync across your devices.
Was this tutorial helpful?
Help us create more free learning resources. Learn more
