Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make IRouteConstraint filter route

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?

like image 928
steinberg Avatar asked Feb 14 '11 01:02

steinberg


People also ask

What is custom routing in MVC?

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.

What is MVC route constraints?

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.

What class would you create to implement a custom constraint for a route segment in asp net core?

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.

Which of the below interface is used to implement custom route constraints?

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.


1 Answers

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() });
like image 71
dahlbyk Avatar answered Sep 24 '22 14:09

dahlbyk