[HttpPut]
[ActionName("Index")]
public ActionResult Change()
{
return View();
}
MVC 中的操作方法选择器只允许您最多有 2 个用于同名方法的操作方法重载。我了解您希望仅使用 {controller}/{id} 作为 URL 路径的来源,但您可能会以错误的方式进行操作。
如果您的控制器只有 2 个操作方法,例如 1 用于 GET,1 用于 PUT,那么您可以将两个操作命名为 Index,就像我在上面所做的那样,或者像这样:
[HttpPut]
public ActionResult Index()
{
return View();
}
如果控制器上有超过 2 个方法,则可以为其他操作创建新的自定义路由。您的控制器可能如下所示:
[HttpPut]
public ActionResult Put()
{
return View();
}
[HttpPost]
public ActionResult Post()
{
return View();
}
[HttpGet]
public ActionResult Get()
{
return View();
}
[HttpDelete]
public ActionResult Delete()
{
return View();
}
...如果您的 global.asax 看起来像这样:
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Get", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("GET") }
);
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Put", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("PUT") }
);
routes.MapRoute(null,
"{controller}", // URL with parameters
new { controller = "Home", action = "Post", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("POST") }
);
routes.MapRoute(null,
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Delete", id = UrlParameter.Optional },
new { httpMethod = new HttpMethodConstraint("DELETE") }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
...这些新的 4 条路由都具有相同的 URL 模式,除了 POST(因为您应该 POST 到集合,但 PUT 到特定的 id)。但是,不同的 HttpMethodConstraints 告诉 MVC 路由只匹配 httpMethod 对应的路由。所以当有人向 /MyItems/6 发送 DELETE 时,MVC 不会匹配前 3 个路由,但会匹配第 4 个。同样,如果有人向 /MyItems/13 发送 PUT,MVC 将不会匹配前 2 个路由,但会匹配第 3 个。
一旦 MVC 匹配路由,它将使用该路由定义的默认操作。因此,当有人发送 DELETE 时,它将映射到控制器上的 Delete 方法。