liveBook · Manning

FromQuery attribute

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

The FromQuery attribute is an ASP.NET Core parameter-binding attribute that specifies binding a parameter from query-string data and can name the query target.

The [FromQuery] attribute tells an ASP.NET Core minimal API to bind a handler parameter from query-string data. It can also name the query key explicitly. section 7.2 section 7.4

Use [FromQuery] when you need to make query binding explicit or separate a parameter name from its query key:

  • Override convention-based binding for simple values such as int and string. section 7.2
  • Bind repeated query values to an array, such as ?id=123&id=456. section 7.4
  • Use Name to keep a descriptive handler parameter while matching the client’s query key. section 7.4
  • Remember that an explicit source takes precedence, and a failed required binding returns 400 Bad Request without trying another source. section 7.8

Rename the handler parameter without changing the URL

app.MapGet("/products/search", ([FromQuery(Name = "id")] int[] ids) => $"Received {ids.Length} ids"); A request to /products/search?id=123&id=456 binds both values to ids, while the handler keeps a clear plural name. section 7.4

Listing 7.1 Binding simple values using [From] attributes
using Microsoft.AspNetCore.Mvc;                                 #1
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
 
app.MapGet("/products/{id}/paged",
    ([FromRoute] int id,                                        #2
     [FromQuery] int page,                                      #3
     [FromHeader(Name = "PageSize")] int pageSize)              #4
     => $"Received id {id}, page {page}, pageSize {pageSize}");
 
app.Run();

Compare explicit binding for route, query-string, and header values in one minimal API endpoint. section 7.2

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

How deep it goes
Explains explicit-source precedence, target naming, repeated-value arrays, and 400 responses, but defers custom binding internals.
Examples
Demonstrates paged product endpoints and repeated product IDs renamed through FromQuery(Name).
What it assumes
Assumes endpoint handlers and query-string syntax while establishing simple-type binding conventions and explicit source selection.
What you can do after
Apply it via ASP.NET Core minimal APIs to select query binding and map repeated or differently named query keys.
How it connects
Connects query binding with model binding, route parameters, FromHeader, FromRoute, arrays, TryParse, and request-body binding.

Also explained in

Compare how 3 books explain FromQuery attribute →

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.