Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's an example of a route like yours, with a constraint on the number:</p> <pre><code>routes.MapRoute( "Question", "questions/{questionID}", new { controller = "StackOverflow", action = "Question" }, new { questionID = @"\d+" } //Regex constraint specifying that it must be a number. ); </code></pre> <p>Here we set the questionID to have at least one number. This will also block out any urls containing anything but an integer, and also prevents the need for a nullable int.</p> <p><em>Note:</em> This does not take into account numbers that larger than the range of Int32 (-2147483647 - +2147483647). I leave this as an exercise to the user to resolve. :)</p> <p>If the user enters the url "questions/foo", they will not hit the Question action, and fall through it, because it fails the parameter constraint. You can handle it further down in a catchall/default route if you want:</p> <pre><code>routes.MapRoute( "Catchall", "{*catchall}", // This is a wildcard routes new { controller = "Home", action = "Lost" } ); </code></pre> <p>This will send the user to the Lost action in the Home controller. More information on the wildcard can be found <a href="http://richarddingwall.name/2008/08/09/three-common-aspnet-mvc-url-routing-issues/" rel="nofollow noreferrer">here</a>.</p> <p><strong>NB: The Catchall should reside as the LAST route.</strong> Placing it further up the chain will mean that this will handle all others below it, given the lazy nature of routes in ASP.NET MVC.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload