在ASP.NET MVC5中,当使用属性路由时,如果有多个匹配的动作,会抛出“歧义动作异常”。为了解决这个问题,可以采取以下几种方法:
routes.MapRoute(
name: "Action1",
url: "controller/action1/{id}",
defaults: new { controller = "Controller", action = "Action1", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Action2",
url: "controller/action2/{id}",
defaults: new { controller = "Controller", action = "Action2", id = UrlParameter.Optional }
);
public class Controller : Controller
{
[ActionName("Action1")]
public ActionResult Action1()
{
// Action1的实现
}
[ActionName("Action2")]
public ActionResult Action2()
{
// Action2的实现
}
}
public class Controller : Controller
{
[HttpGet]
public ActionResult Action1()
{
// Action1的实现
}
[HttpPost]
public ActionResult Action1(FormCollection form)
{
// Action1的实现(处理POST请求)
}
}
通过以上方法,可以避免属性路由中仅有一个匹配动作时的歧义动作异常。请根据实际情况选择适合的方法来解决该问题。