如果您的操作列表(例如Send)是众所周知的,并且它们的(操作)名称不能与某些 ID 值相同,我们可以使用我们的自定义 ConstraintImplementation:
public class MyRouteConstraint : IRouteConstraint
{
public readonly IList<string> KnownActions = new List<string>
{ "Send", "Find", ... }; // explicit action names
public bool Match(System.Web.HttpContextBase httpContext, Route route
, string parameterName, RouteValueDictionary values
, RouteDirection routeDirection)
{
// for now skip the Url generation
if (routeDirection.Equals(RouteDirection.UrlGeneration))
{
return false; // leave it on default
}
// try to find out our parameters
string action = values["action"].ToString();
string id = values["id"].ToString();
// id and action were provided?
var bothProvided = !(string.IsNullOrEmpty(action) || string.IsNullOrEmpty(id));
if (bothProvided)
{
return false; // leave it on default
}
var isKnownAction = KnownActions.Contains(action
, StringComparer.InvariantCultureIgnoreCase);
// action is known
if (isKnownAction)
{
return false; // leave it on default
}
// action is not known, id was found
values["action"] = "Index"; // change action
values["id"] = action; // use the id
return true;
}
并且路线图(在默认路线图之前 - 必须同时提供)应该如下所示:
routes.MapRoute(
name: "DefaultMap",
url: "{controller}/{action}/{id}",
defaults: new { controller = string.Empty, action = "Index", id = string.Empty },
constraints: new { lang = new MyRouteConstraint() }
);
摘要:在这种情况下,我们正在评估“action”参数的值。
- 如果 1) action 和 2) id 都提供了,我们不会在这里处理。
- 也不是已知的动作(在列表中,或反映......)。
- 仅当动作名称未知时,让我们更改路由值:将动作设置为“索引”,将动作值设置为 ID。
注意:action
名称和id
值必须是唯一的......然后这将起作用