这是我的路线:
routes.MapRoute(null, "myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = (string)null }
);
我想添加一个约束,以便类别只能匹配null或三个参数之一(即概述,投影,历史)
答案 0 :(得分:26)
您可以使用UrlParameter.Optional
来允许空值,还可以使用MapRoute
method的constraints
参数..
routes.MapRoute(null,
"myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional },
new { category = "overview|projection|history"}
);
答案 1 :(得分:3)
内联的Regex Gaby会发布。另一种方法是定义自定义IRouteConstraint:
public class FromValuesListConstraint : IRouteConstraint
{
private List<string> _values;
public FromValuesListConstraint(params string[] values)
{
this._values = values.Select(x => x.ToLower()).ToList();
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string value = values[parameterName].ToString();
if (string.IsNullOrWhiteSpace(value))
{
return _values.Contains(string.Empty);
}
return _values.Contains(value.ToLower());
}
}
然后将约束实例传入MapRoute调用:
routes.MapRoute(null,
"myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional },
new { category = new FromValuesListConstraint ("overview", "projection", "history", string.Empty) }
);
答案 2 :(得分:0)
我认为您可能需要使用不同的路线:
routes.MapRoute("Monitor",
"myaccount/monitor", // Matches
new { controller = "MyAccount", action = "Monitor" }
);
routes.MapRoute("MonitorHistory",
"myaccount/monitor/history", // Matches
new { controller = "MyAccount", action = "Monitor", category = "history" }
);
routes.MapRoute("MonitorOverview",
"myaccount/monitor/overview", // Matches
new { controller = "MyAccount", action = "Monitor", category = "overview" }
);
routes.MapRoute("MonitorProjection",
"myaccount/monitor/projection", // Matches
new { controller = "MyAccount", action = "Monitor", category = "projection" }
);
或者 ,您可能需要执行以下操作:
routes.MapRoute("MonitorGlobal",
"myaccount/monitor/{category}", // Matches
new { controller = "MyAccount", action = "Monitor", category = string.Empty }
);
然后在你的控制器中:
public ActionResult Monitor(string category)
{
switch (category)
{
case string.Empty:
// do something
break;
case "overview":
// do something
break;
// so on and so forth
default:
// no match, handle accordingly
break;
}
}