我想我会更进一步,向您展示如何创建路由约束,这样您就不需要注册三个单独的路由。
使用以下文章作为指南,您可以创建一个约束,该约束将根据您将指定的控制器列表验证当前路由控制器:
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-custom-route-constraint-cs
所以这是我的带有路由约束的课程:
public class ControllerConstraint : IRouteConstraint
{
private string[] _controllers;
public ControllerConstraint() : this(null) { }
public ControllerConstraint(string[] controllers)
{
_controllers = controllers;
}
#region IRouteConstraint Members
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
string currentController = values.ContainsKey("controller")? values["controller"].ToString() : null;
return _controllers != null //The list of controllers passed to the route constraint has at least one value in it
&& !String.IsNullOrEmpty(currentController) //The current route data has a controller in it to compare against
&& (from c in _controllers where c.Equals(currentController,StringComparison.CurrentCultureIgnoreCase) select c).ToList().Count > 0; //We find a match of the route controller against the list of controllers
}
#endregion
}
从那里您需要做的就是修改在 Globa.asax 中注册路线的方式
routes.MapRoute(
"Action-less Route", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Questions", action = "Index", id = UrlParameter.Optional}, //Parameter defaults
new {isController = new ControllerConstraint(new string[] {"Questions","Users","Tags"})} //Route Constraint
);
您还可以更进一步,验证 {id} 是一个带有附加路由约束的数字,如下所示:
http://www.asp.net/mvc/tutorials/controllers-and-routing/creating-a-route-constraint-cs