Chapter 15: Generating responses with page handlers in Razor Pages
This chapter introduces how Razor Pages select and run page handlers, bind request data, return results, and improve error responses.
After this chapter you will be able to
- Page handler selection. Explain that routing first selects a Razor Page from its route template and request URL, after which the Razor Pages infrastructure selects one of that page's handlers to execute for the request.
- Handler request data binding. Describe the two request-data binding approaches introduced for page handlers: binding HTTP request values to handler method arguments and binding them to properties on the PageModel.
- Handler results and error pages. Describe that page handlers can return IActionResult objects, including results for HTML and redirects, and that StatusCodePagesMiddleware can turn basic error status responses such as 404 into a friendlier HTML error response by reexecuting the middleware pipeline.
- Page handler responsibilities. Explain that a page handler is a method in a Razor Page's PageModel that runs for a request and acts as Razor Pages' entry point for UI generation. Describe its usual responsibilities: confirming the request is valid, invoking the relevant business logic, and choosing a response type.
- Handler response choices. Describe the common outcomes a page handler can choose: PageResult, no return value through void or Task, or RedirectToPageResult. Explain that PageResult and no return value cause the associated Razor view to generate HTML, whereas RedirectToPageResult sends the user to another page in the application.
- Response selection and rendering. Explain that a page handler does not directly generate the HTTP response or HTML; it selects the response type and prepares data. State that the view engine uses a PageResult to render the Razor view, consistent with MVC's separation between controller-like request handling and view rendering.
- Handler selection inputs. Explain that routing first selects the Razor Page from the request URL, after which EndpointMiddleware selects one page handler to run. State that this selection uses the HTTP verb and the optional handler route value, and that only one handler runs for a request.
- Handler naming convention. Describe the naming convention that maps a verb-handler pair to a method: On followed by the HTTP verb and then the optional handler value. Explain that an Async suffix is optional and ignored for routing, such as OnPostAsync for a POST with no handler value and OnPostCustomSearch for a POST whose handler value is CustomSearch.
- Implicit handler fallback. Explain that when no explicit page handler matches the request’s HTTP verb and handler value, EndpointMiddleware uses an implicit page handler. State that it renders the associated Razor view, takes part in model binding and page filters, but contains no handler logic.
- Razor Pages model binding. Explain model binding as extracting request values and converting them to .NET types in Razor Pages. Describe that values can come from requests such as query strings or form POST bodies, and can be simple or complex types.
- Binding targets and GET behavior. Describe the two Razor Pages binding targets: parameters on a page-handler method and PageModel properties marked with [BindProperty]. State that [BindProperty] does not bind on GET requests by default, unless SupportsGet = true is set.
- Model validity checks. Describe checking ModelState.IsValid before running business logic that depends on model-bound handler values. Explain that an invalid model can lead the handler to return a different response rather than using unavailable or invalid input.
- Handler response return types. Distinguish a handler that returns void to render its associated Razor view from one that returns IActionResult to return response results. Explain that IActionResult is needed when a handler can return different result types, such as Page() on success and RedirectToPage() when the model is invalid.
- IActionResult response execution. Explain that a Razor Page handler returns an IActionResult to choose a response, and that the Razor Pages infrastructure executes that result using the view engine to generate the actual response.
- Response decision separation. Explain how IActionResult separates deciding what response to send from generating that response, and why that separation permits the handler logic and response generation to be tested separately.
- PageResult HTML responses. Explain that a PageResult generates an HTML response by rendering the Razor Page’s associated Razor view, and that it is used whenever a handler returns HTML to the user.
- RedirectToPageResult navigation. Describe that RedirectToPageResult tells the browser to navigate to a new page through an HTTP redirect, commonly after a form submission; the browser automatically follows the redirect.
- Raw status-code results. Describe how a Razor Pages handler can return a NotFoundResult for a missing resource, or a StatusCodeResult with an explicitly chosen status code such as 404. Explain that NotFoundResult sends a raw 404 HTTP status code through the middleware pipeline.
- Status code page handling. Explain what StatusCodePagesMiddleware handles and why a Razor Pages application uses it. Describe when it modifies a response and where it should be placed in the middleware pipeline.
- Pipeline reexecution pages. Describe how UseStatusCodePagesWithReExecute generates a dynamic error page. Explain that it reexecutes the pipeline on a configured error path, can substitute the status code through the {0} token, and preserves the original error status code.
- Reexecution versus redirect. Distinguish UseStatusCodePagesWithReExecute from the redirect-based status-code-page approach. Explain the different request and refresh behavior, why reexecution is generally preferred for an error page in the same application, and when a redirect can be useful.
What it builds on
- Routing requests to Razor Pages (chapter 14) · Routing requests to Razor Pages based on route templates and URLs.
- Handling request logic with page models and handlers (chapter 13) · The role of PageModels and handlers in Razor Pages.
- Combining middleware in a pipeline (chapter 4) · The middleware pipeline that processes requests and generates responses.
- Generating responses with IResult (chapter 5) · The idea of generating responses with result objects.
- Executing a handler using the application model (chapter 13) · The application model's role in executing a Razor Page handler.
- Putting it all together: A complete Razor Page request (chapter 13) · The complete request flow for a Razor Page.
- Understanding the MVC design pattern (chapter 13) · The Model-View-Controller design pattern.
- Building HTML using the view model (chapter 13) · The view model and Razor view's role in building HTML.
Section by section
Introduction
This chapter introduces how Razor Pages select and run page handlers, bind request data, return results, and improve error responses.
- Page handler selection: Explain that routing first selects a Razor Page from its route template and request URL, after which the Razor Pages infrastructure selects one of that page's handlers to execute for the request.
Why it matters: A Razor Page can contain multiple handlers, so selecting the correct handler determines how a request is processed. - Handler request data binding: Describe the two request-data binding approaches introduced for page handlers: binding HTTP request values to handler method arguments and binding them to properties on the PageModel.
Why it matters: Binding makes values sent in an HTTP request available to the code that handles the request. - Handler results and error pages: Describe that page handlers can return IActionResult objects, including results for HTML and redirects, and that StatusCodePagesMiddleware can turn basic error status responses such as 404 into a friendlier HTML error response by reexecuting the middleware pipeline.
Why it matters: Handler results control what the browser receives, while status-code middleware improves the user experience when an error response occurs.
Key terms: Razor Page, page handler, routing, route template, method arguments, PageModel, binding, IActionResult, PageResult, RedirectToPageResult
15.1 Razor Pages and page handlers
This section defines Razor Page handlers as the PageModel entry point for requests, responsible for coordinating validation, application work, and response selection without rendering or implementing business logic themselves.
- Page handler responsibilities: Explain that a page handler is a method in a Razor Page's PageModel that runs for a request and acts as Razor Pages' entry point for UI generation. Describe its usual responsibilities: confirming the request is valid, invoking the relevant business logic, and choosing a response type.
Why it matters: Understanding the handler's role makes it clear where request-specific coordination belongs in a Razor Pages application. - Handler response choices: Describe the common outcomes a page handler can choose: PageResult, no return value through void or Task, or RedirectToPageResult. Explain that PageResult and no return value cause the associated Razor view to generate HTML, whereas RedirectToPageResult sends the user to another page in the application.
Why it matters: A handler's chosen result controls whether the current page is rendered or the user continues to another page. - Response selection and rendering: Explain that a page handler does not directly generate the HTTP response or HTML; it selects the response type and prepares data. State that the view engine uses a PageResult to render the Razor view, consistent with MVC's separation between controller-like request handling and view rendering.
Why it matters: Keeping response selection separate from rendering helps you put code in the correct part of a Razor Pages application. - Business logic separation: Justify keeping business logic out of page handlers by calling application-model services to perform work such as database manipulation or cart-total calculation. Explain that separating concerns this way keeps a growing application testable and maintainable.
Why it matters: Thin handlers are easier to test and change because application rules remain in dedicated classes.
Key terms: page handler, PageModel, application model, PageResult, RedirectToPageResult, void, Task, Razor view, view engine, MVC design pattern
15.2 Selecting a page handler to invoke
This section explains how EndpointMiddleware chooses one Razor Page handler from the request’s HTTP verb and optional handler route value, including its fallback behavior.
- Handler selection inputs: Explain that routing first selects the Razor Page from the request URL, after which EndpointMiddleware selects one page handler to run. State that this selection uses the HTTP verb and the optional handler route value, and that only one handler runs for a request.
Why it matters: A Razor Page can define several handlers, so you need to know what determines which one receives a request. - Handler naming convention: Describe the naming convention that maps a verb-handler pair to a method: On followed by the HTTP verb and then the optional handler value. Explain that an Async suffix is optional and ignored for routing, such as OnPostAsync for a POST with no handler value and OnPostCustomSearch for a POST whose handler value is CustomSearch.
Why it matters: The convention lets you create distinct handlers for different request methods and named operations on one Razor Page. - Handler value sources: Describe how the optional handler route value can come from a handler query-string value, such as /Search?handler=CustomSearch, or from a {handler} route parameter in the page route template. Explain that an optional route parameter can support URLs such as /Search and /Search/CustomSearch.
Why it matters: You can choose whether named page handlers appear as query-string values or as cleaner-looking URL path segments. - Implicit handler fallback: Explain that when no explicit page handler matches the request’s HTTP verb and handler value, EndpointMiddleware uses an implicit page handler. State that it renders the associated Razor view, takes part in model binding and page filters, but contains no handler logic.
Why it matters: A nonmatching verb or handler name does not necessarily produce a missing-handler error; Razor Pages can still render the page through its implicit handler. - HEAD request exception: State the exception for HEAD requests: if no OnHead handler exists, EndpointMiddleware invokes OnGet if it exists instead of using the normal implicit-handler fallback.
Why it matters: This special case explains why a page with only OnGet can also handle a HEAD request.
Key terms: EndpointMiddleware, page handler, HTTP verb, handler route value, RoutingMiddleware, OnGet, OnPostAsync, OnPostCustomSearch, Async suffix, query string
15.3 Accepting parameters to page handlers
This section explains how Razor Pages page handlers receive model-bound request values, validate them, and choose suitable response return types.
- Razor Pages model binding: Explain model binding as extracting request values and converting them to .NET types in Razor Pages. Describe that values can come from requests such as query strings or form POST bodies, and can be simple or complex types.
Why it matters: Model binding lets handler code work with .NET values instead of manually reading raw HTTP request data. - Binding targets and GET behavior: Describe the two Razor Pages binding targets: parameters on a page-handler method and PageModel properties marked with [BindProperty]. State that [BindProperty] does not bind on GET requests by default, unless SupportsGet = true is set.
Why it matters: Choosing a handler parameter or a bindable PageModel property determines where request data becomes available and prevents unintended GET binding. - Model validity checks: Describe checking ModelState.IsValid before running business logic that depends on model-bound handler values. Explain that an invalid model can lead the handler to return a different response rather than using unavailable or invalid input.
Why it matters: Checking model validity keeps a handler from processing request data that failed binding or validation. - Handler response return types: Distinguish a handler that returns void to render its associated Razor view from one that returns IActionResult to return response results. Explain that IActionResult is needed when a handler can return different result types, such as Page() on success and RedirectToPage() when the model is invalid.
Why it matters: The return type must support the response paths a handler needs while still allowing Razor Pages to render or redirect appropriately. - PageModel result helpers: Describe the PageModel helper methods as convenient thin wrappers for creating IActionResult instances. State examples: Page() creates a PageResult, RedirectToPage() creates a RedirectToPageResult, NotFound() creates a NotFoundResult, and StatusCode() creates a StatusCodeResult.
Why it matters: These helpers make common Razor Pages responses concise while still producing standard result objects.
Key terms: model binding, Razor Pages, simple types, complex types, page handler, method arguments, PageModel, [BindProperty], SupportsGet, ModelState
15.4 Returning IActionResult responses
This section introduces IActionResult as the Razor Pages mechanism that represents a handler’s chosen response and explains why it separates response decisions from response generation.
- IActionResult response execution: Explain that a Razor Page handler returns an IActionResult to choose a response, and that the Razor Pages infrastructure executes that result using the view engine to generate the actual response.
Why it matters: This distinction explains why handlers choose responses without having to generate the HTML or HTTP response themselves. - Response decision separation: Explain how IActionResult separates deciding what response to send from generating that response, and why that separation permits the handler logic and response generation to be tested separately.
Why it matters: Separating these responsibilities makes response choices easier to test for given inputs without coupling those tests to generated HTML. - Razor Pages result types: Distinguish IActionResult from the minimal-API IResult interface, and describe the main kinds of IActionResult responses available in Razor Pages, including page rendering, redirects, files, content, and raw status codes.
Why it matters: Choosing the appropriate result type lets a page handler express whether it should render a page, redirect a user, return a file, or report an HTTP outcome.
Key terms: IActionResult, page handler, Razor Pages infrastructure, view engine, MVC design pattern, action method logic, IResult, PageResult, ViewResult, PartialViewResult
15.4.1 PageResult and RedirectToPageResult
This section explains when Razor Page handlers return HTML with PageResult or move the browser to another page with RedirectToPageResult, including the stateless nature of multi-page flows.
- PageResult HTML responses: Explain that a PageResult generates an HTML response by rendering the Razor Page’s associated Razor view, and that it is used whenever a handler returns HTML to the user.
Why it matters: PageResult is the standard result for displaying the HTML pages of a traditional Razor Pages application. - RedirectToPageResult navigation: Describe that RedirectToPageResult tells the browser to navigate to a new page through an HTTP redirect, commonly after a form submission; the browser automatically follows the redirect.
Why it matters: Redirects let a multi-page website move users through flows such as checkout without requiring them to manually follow each step. - Stateless multi-page data: Explain that Razor Pages are generally stateless, so data needed across multiple pages must be persisted in a database or similar store; for a single request, TempData can store small amounts of data in cookies.
Why it matters: Knowing where request data can survive prevents assuming that a value automatically remains available as a user moves between pages.
Key terms: PageResult, Razor view, HTML response, RedirectToPageResult, HTTP redirect, POST, REDIRECT, GET, stateless, TempData, cookies, database
15.4.2 NotFoundResult and StatusCodeResult
This section shows how Razor Pages handlers return raw 404 and other HTTP status-code responses, and why those responses usually need user-friendly handling in web pages.
- Raw status-code results: Describe how a Razor Pages handler can return a NotFoundResult for a missing resource, or a StatusCodeResult with an explicitly chosen status code such as 404. Explain that NotFoundResult sends a raw 404 HTTP status code through the middleware pipeline.
Why it matters: Handlers need a way to communicate failures such as a requested product not existing. - Raw 404 user experience: Explain why returning a raw 404 is usually insufficient for a Razor Pages application: it generates no HTML, so the browser typically shows its generic default error page. Distinguish this web-page concern from an API, where raw status codes are generally acceptable.
Why it matters: A correct HTTP status alone may still leave website users with an unhelpful error page.
Key terms: NotFoundResult, StatusCodeResult, HTTP status code, 404, middleware pipeline, raw 404 status code, HTML, Razor Pages, API, StatusCodePagesMiddleware
15.5 Handler status codes with StatusCodePagesMiddleware
This section explains how StatusCodePagesMiddleware turns empty 4xx and 5xx Razor Pages responses into friendlier error pages, especially by reexecuting the pipeline or redirecting.
- Status code page handling: Explain what StatusCodePagesMiddleware handles and why a Razor Pages application uses it. Describe when it modifies a response and where it should be placed in the middleware pipeline.
Why it matters: Friendly status-code pages keep ordinary errors such as missing URLs from making a user-facing site appear broken. - Pipeline reexecution pages: Describe how UseStatusCodePagesWithReExecute generates a dynamic error page. Explain that it reexecutes the pipeline on a configured error path, can substitute the status code through the {0} token, and preserves the original error status code.
Why it matters: Reexecuting the pipeline lets an application render error pages that match its normal layout while retaining the meaningful HTTP error status. - Reexecution versus redirect: Distinguish UseStatusCodePagesWithReExecute from the redirect-based status-code-page approach. Explain the different request and refresh behavior, why reexecution is generally preferred for an error page in the same application, and when a redirect can be useful.
Why it matters: Choosing reexecution versus redirect affects whether clients retain the actual failure status and whether refreshing retries the original URL. - Error page resilience: Explain the risk of an error-handling path that itself fails and the reason a static error page can be safer than a dynamic one. Describe how StatusCodePagesMiddleware can coexist with exception-handling middleware.
Why it matters: An error page must remain dependable precisely when the rest of the application is already failing.
Key terms: StatusCodePagesMiddleware, UseStatusCodePages, 4xx, 5xx, response body, middleware pipeline, UseStatusCodePagesWithReExecute, reexecute, error handling path, format string token
15.6 Summary
This summary recaps how Razor Page handlers process requests, bind input, choose response results, and handle error status codes.
Where this is used later
- From request to binding model: Making the request useful (chapter 16) · Expands request binding into binding models and binding sources for Razor Pages.
- Selecting a view from an MVC controller (chapter 19) · Uses result selection when MVC controllers choose views.
- Validating binding models (chapter 16) · Handlers use validation results when deciding how to respond.
- Understanding the models in Razor Pages and MVC (chapter 16) · Page handlers and the role of a Razor Page PageModel.
- Views: Rendering the user interface (chapter 17) · Razor views are presented as the component responsible for rendering the user interface.
- Passing data to views (chapter 17) · Data prepared for a view is passed into Razor view rendering.
- Validation in Razor Pages (chapter 16) · Validation occurs before the Razor Page handler discussed in the earlier section.
- Organizing your binding models in Razor Pages (chapter 16) · Organizing binding models relies on separating request-handling concerns from other application concerns.
Concepts explained in this chapter
- PageResultPageResult is an ASP.NET Core action result that renders the associated Razor Page as HTML and returns a successful response.
- RedirectToPageResultRedirectToPageResult is an ASP.NET Core Razor Pages result that instructs the client to navigate to a different page.
- StatusCodePagesMiddlewareStatusCodePagesMiddleware is ASP.NET Core middleware that generates or modifies responses for HTTP status codes, including adding a body to error responses that lack one.
- handlerA handler is an application component that receives a framework-dispatched request or event and performs the corresponding processing.
- http redirectAn HTTP redirect is a response that instructs a client to issue a request for a different URL.
- BindProperty attributeThe BindProperty attribute marks a Razor PageModel property for binding from incoming request data.
- model bindingA model binder is the framework component that locates request values, converts them to appropriate types, and assigns them to bound objects or parameters.
- HTTP 404 errorThe HTTP 404 status code indicates that the server cannot find the resource or endpoint identified by the request path.
- UseStatusCodePagesWithReExecuteUseStatusCodePagesWithReExecute is an ASP.NET Core application-builder extension method that configures status-code middleware to reexecute a request through an error-handling path.
- ModelStateModelState is the ASP.NET Core request-state dictionary that stores bound values and validation errors associated with properties or the model.
- IActionResultIActionResult is an ASP.NET Core interface representing instructions for producing an HTTP response from request-handling code.
- HTTP methodAn HTTP verb is the method token in an HTTP request that indicates the intended operation.
- Razor syntaxA Razor view is a server-rendered template that combines markup with embedded C# expressions and accesses data supplied by an application component.
- endpoint middlewareEndpoint middleware is the ASP.NET Core middleware component that executes the endpoint selected for an incoming request.
- route dataRoute data is a collection of named values supplied to an endpoint route during URL generation.
- post-redirect-getPOST-Redirect-GET is a web interaction pattern in which a successful form submission responds with a redirect to a URL retrieved using GET, preventing refreshes from resubmitting the POST.
- TempDataTempData is an ASP.NET Core temporary-data mechanism that stores small values for retrieval during a subsequent request, commonly using cookies.
- NotFoundResultNotFoundResult is an ASP.NET Core MVC action result representing an HTTP 404 Not Found response.
- StatusCodeResultStatusCodeResult is an ASP.NET Core action result that returns a specified HTTP status code, optionally with response content.
- SupportsGetSupportsGet is a BindProperty setting that permits a Razor Pages property to receive values during GET request model binding.
- 302 foundThe 302 status code is an HTTP response status that temporarily directs a client to retrieve a resource from another location.
- UseStatusCodePagesUseStatusCodePages is an ASP.NET Core application-builder extension method that adds StatusCodePagesMiddleware to the request pipeline.
- error-handling pathAn error handling path is a URL path designated to generate a response for an error status code.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
