Query Strings
Part of the Minimal APIs section of Coddy's ASP.NET Core journey. Lesson 5 of 20.
A query string is the part of an address after ?: name and value pairs joined by &, as in /books?author=austen&page=2. It does not choose the route; it adds options to the request. A lambda parameter whose name is not in the route is read from the query string.
app.MapGet("/books", (string? author, int page = 1) =>
$"Books by {author ?? "anyone"}, page {page}");GET /books?author=austen answers Books by austen, page 1. A parameter that is nullable, like string?, or has a default value is optional. A plain string is required: without it, ASP.NET Core answers 400 Bad Request and the lambda never runs.
Challenge
EasyGET /api/recipes learns to filter: ?category=soup keeps only the soups.
- In
Program.cs, give theGET /api/recipeslambda a parameterstring? category. - Return the recipes whose
Categoryequalscategory. Whencategoryisnull, return every recipe:recipes.Where(r => category is null || r.Category == category).
Try it: press Run. GET /api/recipes?category=soup answers the two soups, ids 1 and 3. Send GET /api/recipes: all three recipes. Send GET /api/recipes?category=dessert: an empty list, [].
Try it yourself
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var recipes = new List<Recipe>
{
new(1, "Tomato Soup", "soup", 25),
new(2, "Pancakes", "breakfast", 15),
new(3, "Lentil Soup", "soup", 40),
};
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", () => recipes);
app.MapGet("/api/recipes/{id:int}", (int id) => recipes.FirstOrDefault(r => r.Id == id));
app.Run();
All lessons in Minimal APIs
2Results and JSON Bodies
Ok and Not Found