To use the Regex source generator, you need .NET 7 and C# 11. Source-generated regexes offer several advantages over traditional regexes:
- Faster startup time: all code is generated at compile time, so there is no need to parse the regex pattern or generate optimized execution code at runtime.
- Better trimming support: unused code is excluded from the final binary.
- Better debugging support: you can step through the generated code and inspect what is happening.
ASP.NET Core routing supports constraints on route parameters, including regex patterns. Since these patterns are usually constant, the source generator is a natural fit. The following example, taken from the documentation, validates 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 code above ensures the value parameter matches an SSN. ASP.NET Core lets you define custom constraints by implementing IRouteConstraint or subclassing an existing implementation. To use the source generator, subclass RegexRouteConstraint and pass a source-generated regex to its 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!