I wrote a custom route constraint, but its filter just doesn't get recognized. Does anyone have an example working use of IRouteConstraint ?
Also, note to developers: I get double display of the form on my android. Something must be wrong with the partial rendering?
A custom route constraint can also be used with a Convention based routing. The new version MVC has an override version MapRoute method that accepts a constraint as a parameter. Using this method we can pass over a custom constraint.
The Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL segment to restrict whether the route will match the request. In simple words, we can say that the Route constraint is a way to put some validation around the defined route.
Implement the IRouteConstraint Match method in ASP.NET Core To create a custom route constraint, you should create a class that extends the IRouteConstraint interface and implements its Match method.
IRouteConstraint interface It defines the contract that a class must implement in order to check whether a URL parameter value is valid for a constraint or not.
Here's a simple constraint that looks up an article slug in a fictional repository:
public class SlugRouteConstraint : IRouteConstraint
{
private readonly ISlugRepository slugRepository = new SlugRepository();
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (!values.ContainsKey(parameterName))
return false;
var slug = (string)values[parameterName];
return slugRepository.Exists(slug);
}
}
You could wire up the constraint like this:
routes.MapRoute("Slugs", "{slug}",
new { controller = "Articles", action = "View" },
new { slug = new SlugConstraint() });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With