tug*_*erk 2 regex asp.net asp.net-mvc asp.net-mvc-routing asp.net-mvc-3
我正在尝试创建一个路由约束但不确定什么是最好的.这是没有约束的路线:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
new { tag = @"" } //Here I would like to put a RegEx for not null match
);
Run Code Online (Sandbox Code Playgroud)
什么是最好的解决方案?
你能创建一个IRouteConstraint:
public class NotNullRouteConstraint : IRouteConstraint
{
public bool Match(
HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return (values[parameterName] != null);
}
}
Run Code Online (Sandbox Code Playgroud)
你可以连线:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
new { tag = new NotNullRouteConstraint() }
);
Run Code Online (Sandbox Code Playgroud)
为什么你需要一个非空/空匹配的约束?通常,如果您定义这样的路线:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
);
Run Code Online (Sandbox Code Playgroud)
并且tag未在请求URL中指定此路由根本不匹配.
如果您想要一个令牌是可选的,那么:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty", tag = UrlParameter.Optional },
);
Run Code Online (Sandbox Code Playgroud)
当您想要将给定路由令牌的值约束为某种特定格式时,将使用约束.
| 归档时间: |
|
| 查看次数: |
3893 次 |
| 最近记录: |