public class CommandConstraint : IRouteConstraint
{
#region Fields
private string[] Matches;
#endregion
#region Constructor
/// <summary>
/// Initialises a new instance of <see cref="CommandConstraint" />
/// </summary>
/// <param name="matches">The array of commands to match.</param>
public CommandConstraint(params string[] matches)
{
Matches = matches;
}
#endregion
#region Methods
/// <summary>
/// Determines if this constraint is matched.
/// </summary>
/// <param name="context">The current context.</param>
/// <param name="route">The route to test.</param>
/// <param name="name">The name of the parameter.</param>
/// <param name="values">The route values.</param>
/// <param name="direction">The route direction.</param>
/// <returns>True if this constraint is matched, otherwise false.</returns>
public bool Match(HttpContextBase context, Route route,
string name, RouteValueDictionary values, RouteDirection direction)
{
if (Matches == null)
return false;
string value = values[name].ToString();
foreach (string match in Matches)
{
if (string.Equals(match, value, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
#endregion
}
然后把我的路线规划成这样:
routes.MapRoute("Search", "Home/{command}",
new
{
controller = "Home",
action = "Index",
command = UrlParameter.Optional
},
new { command = new CommandConstraint("Search") });
routes.MapRoute("Others", "Home/{command}/{id}",
new
{
controller = "Home",
action = "Index",
command = UrlParameter.Optional,
id = UrlParameter.Optional
},
new { command = new CommandConstraint("Delete", "Edit") });
显然,您需要更改索引(…)操作,以便参数名称都是“command”,但这至少可以帮助您朝着正确的方向发展?