说我有以下路线:

routes.MapRoute("Default", "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = "" });


还可以说我的控制器具有以下方法:Index(Int32 id)Edit(Int32 id)

因此/MyController/Index/1是该路由的有效URL。 /MyController/Edit/1也是

但是,如果收到的URL正确映射到我的控制器而不是现有动作,那么我如何定义要执行的“默认动作”,而不是让MVC框架抛出错误屏幕?

基本上,当{action}令牌无法映射到控制器上的现有动作时,我希望URL /MyController/Preview/1/MyController/Whatever/1执行我预先指定的动作。

我看到Codeplex上的MvcContrib项目具有一个属性,使该属性可以与ConventionController一起使用,但是我现在暂时将其保留在纯MS ASP.NET MVC中。

我还看到Fredrik提到了[ControllerAction(DefaultAction = true)]属性,但是除了他的博客(在我的控制器中尝试该应用程序时,我的应用程序将无法编译)之外,在任何地方都找不到该属性。

最佳答案

您现在可以执行以下操作。

protected override void HandleUnknownAction(string actionName) {
  //your code here.
}


另一种方法是,您对默认路由设置了约束,因此它仅与控制器上已知的方法匹配。然后,您可能会有另一条这样的路线:

routes.MapRoute("default-action", "{controller}/{actionName}/{id}", new {action="DefaultAction"});


哪个映射到

public ActionResult DefaultAction(string actionName, string id) {
  //handle default action
}


这将为您提供所需的结果。

关于asp.net-mvc - 如何为我的 Controller 设置一个“默认 Action ”,当没有其他 Action 匹配时将被调用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/300417/

10-10 00:51
查看更多