尽管参数不同,为什么这两个行动被认为是模棱两可的?

Met*_*uru 10 asp.net-mvc action asp.net-mvc-routing

控制器类型'UsersController'上当前的操作请求'Index'在以下操作方法之间是不明确的:System.Web.Mvc.ActionResult类型Controllers.UsersController上的PostUser(Models.SimpleUser)System.Web.Mvc.ActionResult PostUser(Int32) ,Models.SimpleUser)类型Controllers.UsersController

当我尝试使用表单值POST website.com/users/时发生这种情况.

当没有ID(website.com/users/)时,我希望它创建一个新用户,当有一个ID(例如/ users/51)时我希望它更新该用户,那么我该如何让它告诉这两个行动的区别?

以下是两个操作:

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostUser(SimpleUser u)
    {

        return Content("User to be created...");
    }

    [HttpPost]
    [ActionName("Index")]
    public ActionResult PostUser(int id, SimpleUser u)
    {

        return Content("User to be updated...");
    }
Run Code Online (Sandbox Code Playgroud)

这是MapRoute:

    routes.MapRoute(
        "Users",
        "users/{id}",
        new { controller = "Users", action = "Index" }
    );
Run Code Online (Sandbox Code Playgroud)

Dan*_*ung 8

主要问题是两种操作方法之间存在一些歧义,因为模型绑定无法帮助识别路由配置.您当前的路由只是指向索引方法.

您仍然可以使用相同的URL,但以不同的方式命名您的操作然后应用一些新路由会很有帮助.

[HttpPost]
public ActionResult Create(SimpleUser u)
{
    return Content("User to be created...");
}

[HttpPost]
public ActionResult Edit(int id, SimpleUser u)
{
    return Content("User to be updated...");
}
Run Code Online (Sandbox Code Playgroud)

然后在你的路由尝试

routes.MapRoute(
    "UserEdit",
    "users/{id}",
    new { controller = "Users", action = "Edit", 
        httpMethod = new HttpMethodConstraint("POST") });

routes.MapRoute(
    "UserCreate",
    "users",
    new { controller = "Users", action = "Create", 
        httpMethod = new HttpMethodConstraint("POST") });
Run Code Online (Sandbox Code Playgroud)

路由将仅限于POST事件,这意味着您仍然可以在同一路由上为GET方法添加一些路由.比如列表或什么的.

  • 好吧,这就是Out of Box ASP.NET MVC处理每个请求的动作的方式.最后,它归结为它寻找的方法与您正在调用的操作具有匹配的别名,并且与该方法关联的所有属性都返回true.它实际上并不将每个方法的参数视为确定选择哪个动作的方法.因此,当多个方法具有相同的别名并且所有属性在所有方法上都返回true时,框架不知道要调用哪个方法.您可以通过查看MVC源代码中的ControllerActionInvoker.cs类来深入挖掘. (2认同)