A lambda is an anonymous function expression that you can assign to a variable or pass directly as a handler. In ASP.NET Core minimal APIs, it offers a compact way to connect an endpoint with its behavior. section 5.2.3
A lambda as a route handler
app.MapGet("/fruit", () => Fruit.All); uses a lambda with no parameters that returns the fruit collection. You can also assign a parameterized lambda—var getFruit = (string id) => Fruit.All[id];—and pass that variable to MapGet. section 5.2.3
Choose the handler form that keeps the endpoint easiest to understand:
- Use a lambda for small, straightforward handlers. section 5.2.3
- Use a Func<T, TResult>, static method, instance method, or local function when another organization fits better. section 5.2.3
- Use lambdas with Map, Run, and Use to create simple custom middleware. section 31.1
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);
}
}
Compare direct, assigned, static, instance, and local-function handlers in one CRUD API listing. section 5.2.3

















