Skip to content

Instantly share code, notes, and snippets.

@0xced
Created May 17, 2022 21:40
Show Gist options
  • Save 0xced/4288c4a9907500f24990427ba821550c to your computer and use it in GitHub Desktop.
Save 0xced/4288c4a9907500f24990427ba821550c to your computer and use it in GitHub Desktop.
ASP.NET Core route template constraints
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.AspNetCore.Routing.Template;
using Microsoft.Extensions.DependencyInjection;
var provider = new ServiceCollection().AddRouting(_ => {}).BuildServiceProvider();
var templateBinderFactory = provider.GetRequiredService<TemplateBinderFactory>();
const string pattern = "/users/{action:regex(^(get|create)$)}";
var routeTemplate = TemplateParser.Parse(pattern);
var defaults = new RouteValueDictionary();
#if false
var templateBinder = templateBinderFactory.Create(routeTemplate, defaults);
#else
var routePattern = RoutePatternFactory.Parse(pattern);
var templateBinder = templateBinderFactory.Create(routePattern);
#endif
var matcher = new TemplateMatcher(routeTemplate, defaults);
foreach (var path in new[] { "/users/get", "/users/create", "/users/xyz", "/orders/get" })
{
var context = new DefaultHttpContext { Request = { Path = path } };
var values = new RouteValueDictionary();
var match = matcher.TryMatch(path, values);
var success = templateBinder.TryProcessConstraints(context, values, out _, out _);
Console.WriteLine($"{path} {(success ? "✅" : "❌")} ({match})");
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment