Route.Constraints Route.Constraints Route.Constraints Route.Constraints Property

Определение

Получает или задает словарь выражений, задающих допустимые значения для параметра URL-адреса.Gets or sets a dictionary of expressions that specify valid values for a URL parameter.

public:
 property System::Web::Routing::RouteValueDictionary ^ Constraints { System::Web::Routing::RouteValueDictionary ^ get(); void set(System::Web::Routing::RouteValueDictionary ^ value); };
public System.Web.Routing.RouteValueDictionary Constraints { get; set; }
member this.Constraints : System.Web.Routing.RouteValueDictionary with get, set
Public Property Constraints As RouteValueDictionary

Значение свойства

Объект, содержащий имена параметров и выражения.An object that contains the parameter names and expressions.

Примеры

Route В следующем примере показано Constraints, как создать объект и задать свойства, DataTokensи Defaults .The following example shows how to create a Route object and set the Constraints, DataTokens, and Defaults properties.

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);
}
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

В следующем примере Route показан объект, свойство которого Constraints содержит параметр с именем httpMethod и экземпляром HttpMethodConstraint класса для значения.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.

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);
}
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

Комментарии

Constraints Свойство позволяет ограничить допустимые значения параметра URL-адреса, обрабатываемого маршрутом.The Constraints property enables you to limit acceptable values for a URL parameter that is processed by a route. Необходимо назначить RouteValueDictionary объект Constraints свойству.You assign a RouteValueDictionary object to the Constraints property. Каждый элемент в RouteValueDictionary объекте содержит имя параметра и одно из следующих: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.

  • Объект, реализующий IRouteConstraint интерфейс и Match содержащий метод.An object that implements the IRouteConstraint interface and that includes a Match method.

Класс HttpMethodConstraint реализует интерфейс IRouteConstraint.The HttpMethodConstraint class implements the IRouteConstraint interface. Можно включить экземпляр HttpMethodConstraint класса в качестве ограничения, чтобы указать, какие HTTP-команды приемлемы для маршрута.You can include an instance of the HttpMethodConstraint class as a constraint to specify which HTTP verbs are acceptable for the route.

Применяется к

Дополнительно