liveBook · Manning

Optional function argument

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

An optional parameter is a handler or method parameter that may receive no corresponding input and instead accept a null or default value.

An optional function argument lets an ASP.NET Core minimal API handler run when its input is missing. Mark a value-type parameter nullable, such as int?, so model binding supplies null instead of rejecting the request. Nullable complex parameters, such as Product?, likewise receive null when the request body is absent or contains JSON null. section 7.5

Use optional handler arguments when the endpoint should accept either form of input:

  • Combine an optional route placeholder, such as /stock/{id?}, with int? so both /stock/123 and /stock invoke the handler. section 7.5
  • Use a nullable reference type, such as Product?, for an optional body-bound complex value. section 7.5
  • Keep the parameter nonnullable when missing input should produce a 400 Bad Request and prevent the handler from running. section 7.5

Nullable route and body arguments

app.MapGet("/stock/{id?}", (int? id) => $"Received {id}"); app.MapPost("/stock", (Product? product) => $"Received {product}"); The first endpoint accepts /stock/123 and /stock; the second accepts a missing body or JSON null and receives null. section 7.5

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

How deep it goes
Explains nullable syntax and runtime null behavior, while treating default parameter values as a separate feature.
Examples
Demonstrates /stock/{id?} with int?, a nullable Product body, and contrasting required-parameter failure behavior.
What it assumes
Assumes basic handler parameters and binding, while establishing that parameters are required unless marked nullable.
What you can do after
Apply optional arguments via ASP.NET Core minimal APIs to accept missing values and handle null explicitly.
How it connects
Connects route templates, model binding, endpoint routing, nullable reference types, and default parameters.

Also explained in

Compare how 4 books explain optional function argument →

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.