如果我理解得很好,你想限制和对值施加一些约束可以作为路由部分传递,你可以使用 Route Constraint 来做到这一点。请阅读Creating a Route Constraint (C#),您会发现这是怎么可能的。你可以这样做:
routes.MapRoute(
"Product",
"Product/{productId}",
new {controller="Product", action="Details"},
new {productId = @"\d+" }
);
正则表达式 \d+ 匹配一个或多个整数。此约束导致 Product 路由匹配以下 URL:
/产品/3
/Product/8999
但不包括以下网址:
/产品/苹果
/产品
另外您可以编写自定义路由约束,请阅读Creating a Custom Route Constraint (C#) 并查看我刚刚从This post by Guy Burstein 复制的以下示例,我认为您觉得它很有用:
public class FromValuesListConstraint : IRouteConstraint
{
public FromValuesListConstraint(params string[] values)
{
this._values = values;
}
private string[] _values;
public bool Match(HttpContextBase httpContext,
Route route,
string parameterName,
RouteValueDictionary values,
RouteDirection routeDirection)
{
// Get the value called "parameterName" from the
// RouteValueDictionary called "value"
string value = values[parameterName].ToString();
// Return true is the list of allowed values contains
// this value.
return _values.Contains(value);
}
}
正如 Guy 所说:为了实现自定义路由约束,你应该创建一个继承自 IRouteConstraint 的类,并实现 Match 方法。
希望对您有所帮助。