Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using mvc route constraints so a url can only be mapped to one of three possible params

Here is my route:

routes.MapRoute(null, "myaccount/monitor/{category}", // Matches
                new { controller = "MyAccount", action = "Monitor", category = (string)null }
);

I would like to add a constraint so the category can only match a null or one of three params (i.e. overview, projection, history)

like image 928
FiveTools Avatar asked Feb 27 '12 18:02

FiveTools


People also ask

How many routes can be defined in the MVC 3 application?

there are no limits in creating routes. You can create as many route as you want in your RouteConfig.

Can we define multiple route constraints for a route parameter?

We can apply the multiple constraints to a parameter by a colon (:) separator. [Route(URLPath/{parameterName: constrain:Constrain:….})] In the preceding example, the route will only be selected if the parameter id is an integer as well as a value of id greater than 1000.

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.


2 Answers

You can use UrlParameter.Optional to allow nulls, and also use the constraints parameter of the MapRoute method..

 routes.MapRoute(null,
                      "myaccount/monitor/{category}", // Matches
                      new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional  },
                      new { category = "overview|projection|history"}
            );
like image 165
Gabriele Petrioli Avatar answered Oct 21 '22 06:10

Gabriele Petrioli


The inline Regex Gaby posted would work. Another way to do it is to define a custom IRouteConstraint:

public class FromValuesListConstraint : IRouteConstraint
{
    private List<string> _values;

    public FromValuesListConstraint(params string[] values)
    {
        this._values = values.Select(x => x.ToLower()).ToList();
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string value = values[parameterName].ToString();

        if (string.IsNullOrWhiteSpace(value))
        {
            return _values.Contains(string.Empty);
        }

        return _values.Contains(value.ToLower());
    }
}

Then pass in an instance of the constraint into your MapRoute call:

routes.MapRoute(null,
    "myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional  },
new { category = new FromValuesListConstraint ("overview", "projection", "history", string.Empty) }
        );
like image 20
Giscard Biamby Avatar answered Oct 21 '22 05:10

Giscard Biamby