Using source-generated regex in ASP.NET Core route constraints

 
 
  • Gérald Barré

To use the Regex source generator, you need to use .NET 7 and C# 11. Source Generated Regexes provide multiple advantages over traditional regexes:

  • Faster startup time as all the code is generated at compile time. You don't need to parse the regex pattern and generate an optimized code to execute the regex at runtime.
  • Better trimming support as the code is generated at compile time. The code that is not used is not included in the final binary.
  • Better debugging support as the code is generated at compile time. You can step through the code and see what is going on.

ASP.NET Core routing allows setting constraints on the route parameters. The constraint can be a regex pattern. Most of the time, this pattern is constant, so the source generator can be used. For the demo, I'll use the sample from the documentation to validate an SSN (Social Security Number).

C#
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseRouting();

// Use a regex constraint
app.MapGet("{value:regex(^[0-9]{{3}}-[0-9]{{2}}-[0-9]{{4}}$)}", (string value) => "SSN: " + value);

app.Run();

The previous code ensures the value parameter matches an SSN. ASP.NET Core provides a way to create your own constraints by implementing IRouteConstraint or by subclassing a class that implements this interface. In this case, you can use the RegexRouteConstraint and provide a regex in the constructor.

C#
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddRouting(options =>
{
    // Register the "ssn" constraint
    options.ConstraintMap.Add("ssn", typeof(SsnRouteConstraint));
});

var app = builder.Build();
app.UseRouting();

// Use the "ssn" constraint
app.MapGet("{value:ssn}", (string value) => "SSN: " + value);

app.Run();

sealed partial class SsnRouteConstraint : RegexRouteConstraint
{
    [GeneratedRegex("^[0-9]{3}-[0-9]{2}-[0-9]{4}$")]
    private static partial Regex SsnRegex();

    public SsnRouteConstraint()
        : base(SsnRegex())
    {
    }
}

#Additional resources

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub