❔ Manual route/template matching exactly like blazor
I want to take what blazors INavigationManager gives me, which is the ACTUAL uri like this: "/jobadmin/23" and find my @page route TEMPLATE based on it, which looks like this "/jobadmin/{JobNumber:int}".
var routeTemplate = "/jobadmin/{JobNumber:int}";var requestPath = "/jobadmin/23";var template = TemplateParser.Parse(routeTemplate);var matcher = new TemplateMatcher(template, GetDefaults(template));var doesMatch = matcher.TryMatch(requestPath, matcher.Defaults);RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate){ var result = new RouteValueDictionary(); foreach (var parameter in parsedTemplate.Parameters.Where(x => x.DefaultValue is not null)) result.Add(parameter.Name, parameter.DefaultValue); return result;}
var routeTemplate = "/jobadmin/{JobNumber:int}";var requestPath = "/jobadmin/23";var template = TemplateParser.Parse(routeTemplate);var matcher = new TemplateMatcher(template, GetDefaults(template));var doesMatch = matcher.TryMatch(requestPath, matcher.Defaults);RouteValueDictionary GetDefaults(RouteTemplate parsedTemplate){ var result = new RouteValueDictionary(); foreach (var parameter in parsedTemplate.Parameters.Where(x => x.DefaultValue is not null)) result.Add(parameter.Name, parameter.DefaultValue); return result;}
This seems to generally work. I only found one "issue", when I set the requestPath = "/jobadmin/ff", it still matches. I dont know if it should. Its not an int, but it still matches... internally aspnetcore probably just handles that part later. Its fine for me that this is a "match", however it makes me think to make sure.
My question is basically, does this work? Does this do what I think it does?
It can come handy to manually match a request path to route templates, and extract the arguments. This post describes how it can be done with ASP.NET Core.