In ASP.NET 5 the routing system has been unified and it is build as a middleware component that easily can be plugged in. This routing system can be found in the “Microsoft.AspNet.Routing” Nuget Package or add github if you want to work with the source code.

Adding routing Constraints

Here is an example how we putted constraints on our route parameters in MVC 5. In this case the parameter “productId” must match an integer.

routes.MapRoute(
    "Product", 
    "Product/{productId}", 
    defaults: new { controller = "Product", action = "Details" }, 
    constraints: new { productId = @"\d+" });

ASP.NET 5 introduced a new syntax for defining constraints:

“{parameter:constraint}”

parameter will contain the name of the parameter you want to constraint and constraint will specify with constraint will be applied.

routing constraints

For a full overview of the available constraints you can take a look at Microsoft.AspNet.Routing/Constraints.

So the previous constraint will look like this in ASP.NET 5.

routes.MapRoute(
    "Product", 
    "Product/{productId:int}", 
    new { controller = "Product", action = "Details" });

You also can make the parameter “nullable” using “{parameter:constraint?}” syntax.

routes.MapRoute(
    "Product", 
    "Product/{productId:int?}", 
    new { controller = "Product", action = "Details" });

Or pass in a default value “{parameter:constraint=value}”.

routes.MapRoute(
    "Product", 
    "Product/{productId:int=1}", 
    new { controller = "Product", action = "Details" });

Adding your custom constraints

If the buildin constraints don’t meet your needs, you can also create a custom constraint based on the IRouteConstraint interface.

public class AreYouLuckyRouteConstraint : IRouteConstraint
{
    public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection)
        {
            object value;
            if (values.TryGetValue(routeKey, out value) && value != null)
            {
                int result;
                var valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                var isInt =  Int32.TryParse(valueString, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);


            if(isInt)
            {
                Random rand = new Random(10);
                return result == rand.Next(100);
            }
            else
            {
               return false;
            }
        }
        return false;
    }
}

This route constraint will test how lucky you are and will only pass when you passed a correct integer value between the number 0 and 100. Now we need to add our custom constraint to the application route options in the Startup class.

    var routeOptions = app.ApplicationServices.GetService<IOptionsAccessor<RouteOptions>>();
    routeOptions.Options.ConstraintMap.Add("areyoulucky", typeof(AreYouLuckyRouteConstraint));

Now you can use your custom constraint.

routes.MapRoute(
    "Product", 
    "Product/{productId:areyoulucky}", 
    new { controller = "Product", action = "Details" });

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>