A TryParse method converts request text into a typed value and reports whether conversion succeeded. Minimal APIs can then treat the custom type as a simple bindable type. section 7.11 section 7.2
A minimal API uses a TryParse method as follows:
- Define a compatible method such as bool TryParse(string value, out T result), optionally accepting an IFormatProvider. section 7.2
- Return true and assign the parsed value when the input matches the required format. section 7.2
- Return false when the format is invalid; binding then fails and the minimal API returns 400 Bad Request. section 7.11 section 7.2
- Let binding select the route value when the handler parameter name matches a route parameter; otherwise, it checks the query string. section 7.8
Parsing a strongly typed product ID
A ProductId type can accept values such as p123. The endpoint receives a ProductId, while TryParse checks the prefix and parses the remaining integer. A request for /product/p123 succeeds; an invalid value produces 400 Bad Request. section 7.2 section 7.11
Listing 7.2 Implementing TryParse in a custom type to allow parsing from route values
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapGet("/product/{id}", (ProductId id) => $"Received {id}"); #1
app.Run();
readonly record struct ProductId(int Id) #2
{
public static bool TryParse(string? s, out ProductId result) #3
{
if(s is not null #4
&& s.StartsWith('p') #4
&& int.TryParse( #5
s.AsSpan().Slice(1), #6
out int id)) #7
{
result = new ProductId(id); #8
return true; #8
}
result = default; #9
return false; #9
}
}
Inspect the complete minimal API example, including the ProductId record struct, TryParse implementation, and route endpoint. section 7.2
