Skip to content

Instantly share code, notes, and snippets.

@Grinderofl
Created May 31, 2019 09:12
Show Gist options
  • Save Grinderofl/186a76202db8d80443557532816c26bb to your computer and use it in GitHub Desktop.
Save Grinderofl/186a76202db8d80443557532816c26bb to your computer and use it in GitHub Desktop.
Custom route constraint
public class PageRouteConstraint : IRouteConstraint
{
private static readonly Regex regex = new Regex($"^page=(\\d+)$");
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection != RouteDirection.IncomingRequest || !values.TryGetValue(routeKey, out var page))
{
return false;
}
var segment = page.ToString();
var match = regex.Match(segment);
if (match.Success)
{
values[routeKey] = match.Groups[1];
}
return true;
}
}
// ConfigureServices
services.AddRouting(x =>
{
x.ConstraintMap.Add("page", typeof(PageRouteConstraint));
});
// Configure
app.UseMvc(routes =>
{
routes.MapRoute("myRoute", "{controller}/{action}/{page:page?}/");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment