Bart Calixto
Bart Calixto

Reputation: 19705

How to constraint route value to a valid int32 on ASP.NET MVC4

Having this default route :

    routes.MapRoute(
        name: "Default", // Route name
        url: "{controller}/{action}/{id}", // URL with parameters
        defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
        constraints: new {id = @"\d+"}
    );

The constraints works ok, but the id is an int on controller. So if I pass /Controller/Action/2147483648 is a valid \d+ regex but it's not a valid Int32, so that returns a 500 server error and I want it to restrict so that it returns a 404.

How can I make the constraints so it only allow valid positive int values ? which are from 0 to 2,147,483,647 ?

Upvotes: 2

Views: 1531

Answers (1)

asymptoticFault
asymptoticFault

Reputation: 4529

You could create a custom route constraint like this:

public class MaxIntConstraint : IRouteConstraint
{
    public bool Match (HttpContextBase httpContext, Route route, string parameterName, 
                       RouteValueDictionary values, RouteDirection routeDirection)
    {
        // just use int.TryParse because if it can't fit it won't parse
        int val;
        return int.TryParse(values[parameterName].ToString(), out val);
    }
}

And your route would look like this:

routes.MapRoute(
    name: "Default", // Route name
    url: "{controller}/{action}/{id}", // URL with parameters
    defaults: new { controller = "Application", action = "Index", id = 0 }, // Parameter defaults
    constraints: new { id = new MaxIntConstraint() }
);

Of course the constraint is very specific and could be spruced up with some more error checking but you get the idea.

Upvotes: 7

Related Questions