我正在尝试创建一个路由约束,但不确定哪个最适合这个。这是没有约束的路线:
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
);
对此最好的解决方案是什么?
答案 0 :(得分:8)
您可以创建IRouteConstraint
:
public class NotNullRouteConstraint : IRouteConstraint
{
public bool Match(
HttpContextBase httpContext, Route route, string parameterName,
RouteValueDictionary values, RouteDirection routeDirection)
{
return (values[parameterName] != null);
}
}
你可以连线:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
new { tag = new NotNullRouteConstraint() }
);
答案 1 :(得分:6)
为什么你需要一个非空/空匹配的约束?通常,如果您定义这样的路线:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty" },
);
并且请求网址中未指定tag
此路由根本不匹配。
如果你想要一个令牌是可选的,那么:
context.MapRoute(
"Accommodation_accomm_tags",
"accomm/{controller}/{action}/{tag}",
new { action = "Tags", controller = "AccommProperty", tag = UrlParameter.Optional },
);
当您想要将给定路由令牌的值约束为某种特定格式时,会使用约束。
答案 2 :(得分:2)
首先,我尝试为空字符串创建一个RegEx,它是^$
(这将是null)。但是,路径约束看起来不像!=
。如何将一个或多个角色与^.+$
匹配?
所以:
tag = @"^.+$"