如何使 MVC 丢弃使用约束中指定之外的动词的请求?
在我的 MVC 应用程序中,我想要的行为与之前在 web.config 中的
中指定的行为相同,即如果我注册这样的处理程序:
<system.webServer>
<handlers>
<add name="processData" verb="POST" path="processData" type="RightType, RightAssembly"/>
</handlers>
</system.webServer>
那么所有请求都会发送到 /processData
具有除“POST”之外的动词会导致 HTTP 404。
我尝试注册这样的路由:
routes.MapRoute(
@"ProcessData", @"processData",
new { controller = @"Api", action = @"ProcessData" },
new { httpMethod = new HttpMethodConstraint( "POST" ) } );
现在,一旦请求具有除 POST 之外的动词,路由就会不匹配,路由解析会失败并继续使用默认值页。
一旦路径匹配但动词不匹配,如何使 MVC 生成 HTTP 错误消息(代码 404 或类似的内容)?
In my MVC application I want behavior as was previously specified in <httpHandlers>
in web.config, namely that if I register a handler like this:
<system.webServer>
<handlers>
<add name="processData" verb="POST" path="processData" type="RightType, RightAssembly"/>
</handlers>
</system.webServer>
then all requests to /processData
that have verbs other than "POST" result in HTTP 404.
I tried to register a route like this:
routes.MapRoute(
@"ProcessData", @"processData",
new { controller = @"Api", action = @"ProcessData" },
new { httpMethod = new HttpMethodConstraint( "POST" ) } );
and now once a request has a verb other than POST the route isn't matched, route resolution falls through and proceeds to the default page.
How do I make MVC produce an HTTP error message (code 404 or anything like that) once a path matches but a verb mismatches?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用您不想要的动词注册另一条路线,并使其导致 NotFound 操作。
You could just register another route with the verbs that you don't want and make that lead to a NotFound action.
路由的工作原理是按照指定的顺序跟踪路由,直到找到匹配的路由。通过添加约束,您会使该路由失败,因此它会沿着列表查找下一个匹配的路由(您的默认路由)。
要获得您想要的行为,您需要让您的路由捕获请求,然后处理错误。
将约束从路由中取出,并在控制器上执行以下操作:
我假设您在此处对操作方法进行模型绑定,因为您确实需要不同的方法签名。如果没有,那么您需要取消 HttpPost 属性并在那里测试请求方法。
Routing works by following routes in the order specified until it finds one that matches. By adding the constraint you make this route fail and so it goes down the list to find the next matching route (your default).
To get the behaviour you want you need to have your route catch the request and then handle the error.
Take the constraint out of the route and on your controller do the following:
I am assuming that you do model binding on your action method here because you do need differing method signatures. If not then you'll need to take off the HttpPost attribute and test for the request method there.