我希望保持ASP.NET MVC4现有的控制器/动作/id路由,默认控制器=主页,默认动作=索引,但也允许控制器/id路由到控制器的索引方法,只要第二项不是已知的动作。
例如,给定一个具有操作Index和Send的控制器Home:
/Home/Send -> controller's Send method
/Home -> controller's Index method
/Home/Send/xyz -> controller's Send method with id = xyz
/Home/abc -> controller's Index method with id = abc但是,如果我先定义任何一个路由,它就会隐藏另一个路由。我该怎么做呢?
发布于 2012-12-12 15:15:46
如果您的操作列表(例如发送)是众所周知的,并且它们的(操作)名称不能与某个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() }
);汇总操作:在本例中,我们计算的是“”参数的值。
”,并将操作值设置为ID。
注意:action名称和id值必须是唯一的...那么这将会起作用
发布于 2012-12-12 03:26:26
在缺省的泛型之前先做特定的。顺序很重要。
routes.MapRoute(name: "single", url: "{controller}/{id}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { id = @"^[0-9]+$" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home",
action = "Index",
id = UrlParameter.Optional }
);发布于 2017-07-01 19:08:35
最简单的方法是在您的控制器中创建两个Action方法。一个用于Index,另一个用于Send,并将string id参数放在这两个参数上。因为您不能有重复或重载的操作方法,这就解决了这个问题。Index方法现在将处理id存在或不存在的索引或空路径(null),并以这种方式处理视图。您的Send方法将执行与Index完全相同的操作。然后,您可以根据id是否为空,按自己喜欢的方式进行路由、处理或重定向。这应该可以在不更改RouteConfig.cs的情况下工作:
public ActionResult Index(string id) {if (id == null) Do A else Do B}
public ActionResult Send(string id) {if (id == null) Do A else Do B}我为此挣扎了很长一段时间,这是最简单的解决方案。
https://stackoverflow.com/questions/13827002
复制相似问题