为什么 MVC 操作方法选择器没有选择我的 HttpPut 操作?
给定以下路线:
context.MapRoute(null, "widgets",
new { controller = "Widgets", action = "Add" },
new { httpMethod = new HttpMethodConstraint("PUT") });
和以下控制器:
public class WidgetsController
{
[HttpPut]
public ActionResult Add(WidgetForm model)
{
return DoStuff(); // code here doesn't matter
}
}
以及呈现以下表单的视图(使用 [email protected](HttpVerbs.Put)
:
<form action="/widgets" method="post">
<!-- many form elements, then -->
<input name="X-HTTP-Method-Override" type="hidden" value="PUT" />
</form>
提交表单时,MVC操作方法选择器 。如果我在左大括号上设置断点,则它永远不会在浏览器中返回 404 页面(我相信这是默认的 ActionNotFound 行为)。
不选择上面的操作方法 使用以下路由添加 HttpPut 方法:
context.MapRoute(null, "widgets",
new { controller = "Widgets", action = "Add" },
new { httpMethod = new HttpMethodConstraint("PUT", "POST") });
这似乎不对......对我来说,我应该能够在没有 POST 约束的情况下执行此操作,那么为什么应该使用 HttpPost 进行修饰。 POST 约束有必要吗?
Given the following route:
context.MapRoute(null, "widgets",
new { controller = "Widgets", action = "Add" },
new { httpMethod = new HttpMethodConstraint("PUT") });
And the following controller:
public class WidgetsController
{
[HttpPut]
public ActionResult Add(WidgetForm model)
{
return DoStuff(); // code here doesn't matter
}
}
And a view that renders the following form (using [email protected](HttpVerbs.Put)
:
<form action="/widgets" method="post">
<!-- many form elements, then -->
<input name="X-HTTP-Method-Override" type="hidden" value="PUT" />
</form>
When the form is submitted, the MVC action method selector does not choose the above action method. If I set a breakpoint on the opening brace, it is never hit. In browser, it returns 404 page (I believe this is the default ActionNotFound behavior).
However, the action method selector does choose the Add HttpPut method with the following route:
context.MapRoute(null, "widgets",
new { controller = "Widgets", action = "Add" },
new { httpMethod = new HttpMethodConstraint("PUT", "POST") });
This doesn't seem right... is it? It seems to me that I should be able to do this without a POST constraint. The action method is not decorated with HttpPost, so why should the POST constraint be necessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是对的。更深入地了解它在 MVC 管道中的工作原理,实际上是 MVC(ActionMethodSelectorAttribute、ActionInvoker、RedirectToRoute)处理此问题,而不是 RouteModule。
所以在路由模块中,它仍然是一个“POST”请求,而不是“PUT”。
Its right. Looking a bit deeper into how this works in the MVC pipeline it's actually MVC (ActionMethodSelectorAttribute, ActionInvoker,RedirectToRoute) that handles this and not the RouteModule.
So in route module, it's still a "POST" request, not a "PUT".