Skip to content

Instantly share code, notes, and snippets.

@KeesCBakker
Created February 19, 2018 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KeesCBakker/4774c36c637ada7eb41d19b586494010 to your computer and use it in GitHub Desktop.
Save KeesCBakker/4774c36c637ada7eb41d19b586494010 to your computer and use it in GitHub Desktop.
public class RegexNamedGroupRoutingConstraint : IRouteConstraint
{
private readonly List<Regex> regexes = new List<Regex>();
public RegexNamedGroupRoutingConstraint(params string[] regexes)
{
foreach (var regex in regexes)
{
this.regexes.Add(new Regex(regex));
}
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values[routeKey] == null)
{
return false;
}
var url = values[routeKey].ToString();
foreach (var regex in regexes)
{
var match = regex.Match(url);
if (match.Success)
{
foreach (Group group in match.Groups)
{
values.Add(group.Name, group.Value);
}
return true;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment