Route.Constraints Property
Gets or sets a dictionary of expressions that specify valid values for a URL parameter.
Assembly: System.Web (in System.Web.dll)
Property Value
Type: System.Web.Routing.RouteValueDictionaryAn object that contains the parameter names and expressions.
The Constraints property enables you to limit acceptable values for a URL parameter that is processed by a route. You assign a RouteValueDictionary object to the Constraints property. Each element in the RouteValueDictionary object contains the name of a parameter and one of the following:
A string that defines a regular expression. The regular expression is case-insensitive.
An object that implements the IRouteConstraint interface and that includes a Match method.
The HttpMethodConstraint class implements the IRouteConstraint interface. You can include an instance of the HttpMethodConstraint class as a constraint to specify which HTTP verbs are acceptable for the route.
The following example shows how to create a Route object and set the Constraints, DataTokens, and Defaults properties.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) RegisterRoutes(RouteTable.Routes) End Sub Shared Sub RegisterRoutes(ByVal routes As RouteCollection) Dim urlPattern As String Dim reportRoute As Route urlPattern = "{locale}/{year}" reportRoute = New Route(urlPattern, New ReportRouteHandler) reportRoute.Defaults = New RouteValueDictionary(New With {.locale = "en-US", .year = DateTime.Now.Year.ToString()}) reportRoute.Constraints = New RouteValueDictionary(New With {.locale = "[a-z]{2}-[a-z]{2}", .year = "\d{4}"}) reportRoute.DataTokens = New RouteValueDictionary(New With {.format = "short"}) routes.Add(reportRoute) End Sub
The following example shows a Route object whose Constraints property contains a parameter named httpMethod with an instance of the HttpMethodConstraint class for the value.
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) RegisterRoutes(RouteTable.Routes) End Sub Shared Sub RegisterRoutes(ByVal routes As RouteCollection) Dim urlPattern As String Dim reportRoute As Route Dim allowedMethods() As String = {"GET", "POST"} Dim methodConstraints As HttpMethodConstraint methodConstraints = New HttpMethodConstraint(allowedMethods) Dim constraintValues = New With {.httpMethod = methodConstraints} urlPattern = "{locale}/{year}" reportRoute = New Route(urlPattern, New ReportRouteHandler) reportRoute.Constraints = New RouteValueDictionary(constraintValues) routes.Add(reportRoute) End Sub
Available since 3.5