Blazor内部的方法不对外公开,要么反射,要么自己写
写的不好,参考自https://q.cnblogs.com/q/146281 ,有一点改动。
这个其实是适合后端的,比Blazor的路由约束支持要多,判定上可能会出现失误。
而且"Microsoft.AspNetCore.Routing" Version="2.2.2"包已过时了
public class RouteHelper
{
private readonly List<string> routeTemplates = [];
public RouteHelper(Assembly[] assemblies)
{
routeTemplates = GetRouteTemplates(assemblies);
}
public bool IsMatch(string url)
{
// https://q.cnblogs.com/q/146281
var urlPath = new Uri(url).AbsolutePath;
IServiceCollection services = new ServiceCollection();
services.AddOptions<RouteOptions>();
using ServiceProvider sp = services.BuildServiceProvider();
var routeOptions = sp.GetRequiredService<IOptions<RouteOptions>>();
var constraintResolver = new DefaultInlineConstraintResolver(routeOptions, sp);
foreach (string routeTemplate in routeTemplates)
{
var parsedTemplate = TemplateParser.Parse(routeTemplate);
var values = new RouteValueDictionary();
var matcher = new TemplateMatcher(parsedTemplate, values);
if (matcher.TryMatch(urlPath, values))
{
if (parsedTemplate.Parameters.Count == 0)
{
return true;
}
foreach (var parameter in parsedTemplate.Parameters)
{
if (!parameter.InlineConstraints.Any())
{
return true;
}
foreach (var inlineConstraint in parameter.InlineConstraints)
{
var routeConstraint = constraintResolver.ResolveConstraint(inlineConstraint.Constraint);
var routeDirection = RouteDirection.IncomingRequest;
bool matched = routeConstraint!.Match(httpContext: null, route: null, parameter.Name!, values, routeDirection);
if (matched)
{
return true;
}
}
}
}
}
return false;
}
public static List<string> GetRouteTemplates(Assembly[] assemblies)
{
var routes = new List<string>();
foreach (var assembly in assemblies)
{
foreach (var type in assembly.GetTypes())
{
var routeAttribute = type.GetCustomAttribute<RouteAttribute>();
if (routeAttribute != null)
{
routes.Add(routeAttribute.Template);
}
}
}
return routes;
}
}
标签:return,url,assemblies,foreach,var,new,Blazor,public,路由
From: https://www.cnblogs.com/Yu-Core/p/18260711