C
C#2y ago
Maskoe

❔ 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}". I found this post https://blog.markvincze.com/matching-route-templates-manually-in-asp-net-core/ and played around with the code, adjusted it a little and now I got the following:
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?
Matching route templates manually in ASP.NET Core
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.
1 Reply
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server