在情況下,你的行爲(如發送)的列表中是衆所周知的,而他們(行動)名稱不能是一樣的,有些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() }
);
總和mary:在這種情況下,我們正在評估「action」參數的值。
- 如果同時提供1)action和2)id,我們將不會在這裏處理它。
- 如果這是已知的行爲(在列表中,或反映...)。
- 只有當動作名稱未知時,讓我們更改路由值:將動作設置爲「索引」並將動作值設置爲ID。
注:action
名稱和id
值必須是唯一的......那麼這將工作
你是如何在RouteTable上定義你的路線的? –
@FelipeOriani我沒有 - 如果我創建一個,它會隱藏另一個,據我所知。 –