【发布时间】:2011-07-06 20:39:54
【问题描述】:
我有一个 ASP.net MVC 3 站点,其路由如下:
routes.MapRoute("Get", "endpoint/{id}",
new { Controller = "Foo", action = "GetFoo" },
new { httpMethod = new HttpMethodConstraint("GET") });
routes.MapRoute("Post", "endpoint/{id}",
new { Controller = "Foo", action = "NewFoo" },
new { httpMethod = new HttpMethodConstraint("POST") });
routes.MapRoute("BadFoo", "endpoint/{id}",
new { Controller = "Error", action = "MethodNotAllowed" });
routes.MapRoute("NotFound", "",
new { controller = "Error", action = "NotFound" });
所以简而言之,我有一个匹配某些 HTTP 动词(如 GET 和 POST)的路由,但在其他 HTTP 动词(如 PUT 和 DELETE)上它应该返回一个特定的错误。
我的默认路由是 404。
如果我删除“BadFoo”路由,那么针对端点/{id} 的 PUT 会返回 404,因为没有其他路由匹配,所以它转到我的 NotFound 路由。
问题是,我有很多像 Get 和 Post 这样的路由,我有一个 HttpMethodConstraint 并且我必须创建一个像 BadFoo 路由这样的路由,只是为了在路由字符串上而不是在 Method 上捕获正确的匹配,这会不必要地破坏我的路由。
如何设置仅使用 Get、Post 和 NotFound 路由的路由,同时仍然区分 HTTP 404 未找到(=无效 URL)和 HTTP 405 方法不允许(=有效 URL,错误 HTTP 方法)?
【问题讨论】:
-
如果你用 [HttpGet] 和 [HttpPost] 明确地标记你的控制器方法而不是使用路由会发生什么?这会使 PUT 和 DELETE 请求抛出正确的异常吗?
-
有人将此作为 MS Connect 上的错误提出(我同意,在这种情况下他们没有正确实现 HTTP 响应代码)。然而,它被设计为关闭 - 显然他们宁愿你为所有动词编写单行“不允许抛出 405 方法”控制器方法。但我更喜欢 Max 在下面的解决方法。链接:connect.microsoft.com/VisualStudio/feedback/details/419729/…
标签: .net asp.net-mvc asp.net-mvc-3 routing asp.net-mvc-routing