อ่านในภาษาอังกฤษ แก้ไข

แชร์ผ่าน


Route.Constraints Property

Definition

Gets or sets a dictionary of expressions that specify valid values for a URL parameter.

C#
public System.Web.Routing.RouteValueDictionary Constraints { get; set; }

Property Value

An object that contains the parameter names and expressions.

Examples

The following example shows how to create a Route object and set the Constraints, DataTokens, and Defaults properties.

C#
void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
    reportRoute.Defaults = new RouteValueDictionary { { "locale", "en-US" }, { "year", DateTime.Now.Year.ToString() } };
    reportRoute.Constraints = new RouteValueDictionary { { "locale", "[a-z]{2}-[a-z]{2}" }, { "year", @"\d{4}" } };
    reportRoute.DataTokens = new RouteValueDictionary { { "format", "short" } };
    routes.Add(reportRoute);
}

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.

C#
void Application_Start(object sender, EventArgs e) 
{
    RegisterRoutes(RouteTable.Routes);
}

public static void RegisterRoutes(RouteCollection routes)
{
    string[] allowedMethods = { "GET", "POST" };
    HttpMethodConstraint methodConstraints = new HttpMethodConstraint(allowedMethods);

    Route reportRoute = new Route("{locale}/{year}", new ReportRouteHandler());
    reportRoute.Constraints = new RouteValueDictionary { { "httpMethod", methodConstraints } };

    routes.Add(reportRoute);
}

Remarks

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.

Applies to

ผลิตภัณฑ์ เวอร์ชัน
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

See also