liveBook · Manning

TryParse method

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

A TryParse method is a parsing method that converts text to a typed value and reports success through a Boolean return value and an output result.

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

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

How deep it goes
Defines supported signatures and demonstrates validation, conversion, binding selection, and 400 responses without covering custom binding internals.
Examples
Uses a ProductId record struct that parses p-prefixed integers from a route.
What it assumes
Assumes basic C# types and endpoint handlers while introducing custom parsing and simple-type binding through a concrete example.
What you can do after
Build it from scratch by adding TryParse to a custom type and accepting that type in a minimal API handler.
How it connects
Connects TryParse with model binding, minimal APIs, route values, query strings, and strongly typed IDs.

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.