Nullable reference types (NRTs) are a C# compiler feature for stating whether reference-type values may be null. They help reduce null-reference exceptions by making optionality explicit and enabling compiler and IDE warnings. section 7.5 section 4.4
Use nullable annotations to make request-handling behavior match the values an endpoint can receive:
- Mark an optional reference-type parameter with ?, such as Product?, when a missing or literal null request body should become a null handler argument. section 7.5
- Keep NRTs enabled where possible; ASP.NET Core .NET 7 templates enable them by default, and disabling them can make types unexpectedly optional. section 7.5
- Enable the feature in the project file with <Nullable>enable</Nullable>, or selectively with #nullable enable when whole-project activation is not practical. section 7.5 section 3.5
- Use compiler analyzers and IDE hints to find mismatches between endpoint optionality and handler parameters before runtime. section 7.5
Listing 7.5 Using optional parameters in endpoint handlers
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapGet("/stock/{id?}", (int? id) => $"Received {id}"); #1
app.MapGet("/stock2", (int? id) => $"Received {id}"); #2
app.MapPost("/stock", (Product? product) => $"Received {product}"); #3
app.Run();
Shows nullable route, query-string, and body parameters in a small minimal API application. section 7.5

