In this tutorial,
Stephen Walther demonstrates how you can control how browser requests
match routes by creating route constraints with regular expressions.
You use route constraints to restrict
the browser requests that match a particular route. You can use a regular
expression to specify a route constraint. For example, imagine that you have defined the route in Listing 1 in your Global.asax file.
Listing 1 - Global.asax.vb
routes.MapRoute( _
"Product", _
"Product/{productId}", _
New With {.controller = "Product", .action = "Details"} _
)
Listing 1 contains a route named Product. You can use the Product route to map browser requests to the ProductController contained in Listing 2.
Listing 2 - Controllers\ProductController.vb
Public Class ProductController
Inherits System.Web.Mvc.Controller
Function Details(ByVal productId As Integer) As ActionResult
Return View()
End Function
End Class
Notice that the Details() action exposed by the Product controller accepts a single parameter named productId. This parameter is an integer parameter.
The route defined in Listing 1 will match any of the following URLs:
- /Product/23
- /Product/7
- /Product/blah
- /Product/apple
Figure 01: Seeing a page explode (Click
to view full-size image)
Listing 3 - Global.asax.vb
routes.MapRoute( _
"Product", _
"Product/{productId}", _
New With {.controller = "Product", .action = "Details"}, _
New With {.productId = "\d+"} _
)
The regular expression \d+ matches one or more integers. This constraint causes the Product route to match the following URLs:
- /Product/3
- /Product/8999
- /Product/apple
- /Product
0 comments:
Post a Comment