Created
May 31, 2019 09:12
-
-
Save Grinderofl/186a76202db8d80443557532816c26bb to your computer and use it in GitHub Desktop.
Custom route constraint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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