liveBook · Manning

Handler

As explained in ASP.NET Core in Action, 3e

A handler is an application component that receives a framework-dispatched request or event and performs the corresponding processing.

A handler is the code that runs for a selected HTTP request. Routing matches the request to an endpoint; endpoint middleware invokes its handler and uses the result to produce a response. In a minimal API, the handler belongs to an endpoint. In Razor Pages, it is a method on a page’s PageModel. section 6.1 section 13.1.4

A minimal API handler can be a lambda, local function, static method, or method on an object. These forms work the same way, so choose the one that keeps the endpoint clear. Handler parameters can receive values from the request, such as a route value or an object deserialized from a JSON body. A registered service can also be supplied through dependency injection. section 5.2.3 section 8.5

Listing 5.2 Creating route handlers for a simple CRUD API
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.MapGet("/fruit", () => Fruit.All);                          #1
 
var getFruit = (string id) => Fruit.All[id];                    #2
app.MapGet("/fruit/{id}", getFruit);                            #2
 
app.MapPost("/fruit/{id}", Handlers.AddFruit);                  #3
 
Handlers handlers = new();                                      #4
app.MapPut("/fruit/{id}", handlers.ReplaceFruit);               #4
 
app.MapDelete("/fruit/{id}", DeleteFruit);                      #5
 
app.Run();
 
void DeleteFruit(string id)                                     #5
{
    Fruit.All.Remove(id);
}
 
record Fruit(string Name, int Stock)
{
    public static readonly Dictionary<string, Fruit> All = new();
};
 
class Handlers
{
    public void ReplaceFruit(string id, Fruit fruit)            #6
    {
        Fruit.All[id] = fruit;
    }
 
    public static void AddFruit(string id, Fruit fruit)         #7
    {
        Fruit.All.Add(id, fruit);
    }
}

The fruit CRUD API pairs HTTP verbs and routes with five different handler forms. Compare the mappings first; the forms differ, but each supplies the code for its endpoint. section 5.2.3

A Razor Page can have several handlers, but only one runs for a request. Routing first selects the page. Endpoint middleware then chooses a method using the HTTP verb and an optional handler value: OnGet handles a GET, while OnPostCustomSearch names a particular POST handler. The handler value can come from a query string or a {handler} route parameter. section 14.3 section 15.2

Keep a page handler focused on coordinating the request:

  • Check the request’s validity, including ModelState after automatic validation; the handler still runs when validation fails. section 13.4.2 section 16.3.2
  • Call an application service for business logic rather than doing that work directly in the handler. section 13.4.2 section 15.1
  • Choose the response. Page() or a void return renders the associated view; RedirectToPage() sends the user to another page. The handler selects the response but does not generate the HTML itself. section 15.1 section 15.6

Handling a submitted form

A checkout page’s OnPost handler checks ModelState.IsValid. If validation failed, it returns Page() so the form can display errors. After a successful submission, it returns RedirectToPage("Success"). section 16.3.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Works through handler forms, selection conventions, binding, delegation, validation, and response choices in small applications.
Examples
Uses a fruit CRUD API, a to-do category page, a search page with multiple handlers, and a checkout form.
What it assumes
Builds from basic minimal API endpoints and a template-created Razor Pages application before introducing page-handler conventions.
What you can do after
Build it from scratch by mapping minimal API handlers or writing Razor Page methods that delegate work and select responses.
How it connects
Connects routing, endpoint middleware, model binding, dependency injection, validation, application services, and Razor views.

Also explained in

Compare how 22 books explain handler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.