这是我在Global.asax的路线
routes.MapRoute("PizzaGet","pizza/{pizzaKey}",new { controller = "Pizza",action = "GetPizzaById" }); routes.MapRoute("DeletePizza",action = "DeletePizza" });
这是我的控制器方法
[AcceptVerbs(HttpVerbs.Get)] public ActionResult GetPizzaById(long pizzaKey) [AcceptVerbs(HttpVerbs.Delete)] public ActionResult DeletePizza(long pizzaKey)
当我做一个GET它返回的对象,但是当我做一个DELETE我得到一个404.似乎这应该工作,但它没有。
如果我切换两个路由,那么我可以执行DELETE,但是在GET上获得404。
现在这真的很美。谢谢
routes.MapRoute("Pizza-GET",action = "GetPizza"},new { httpMethod = new HttpMethodConstraint(new string[]{"GET"})}); routes.MapRoute("Pizza-UPDATE",action = "UpdatePizza" },new { httpMethod = new HttpMethodConstraint(new string[] { "PUT" }) }); routes.MapRoute("Pizza-DELETE",action = "DeletePizza" },new { httpMethod = new HttpMethodConstraint(new string[] { "DELETE" }) }); routes.MapRoute("Pizza-ADD","pizza/",action = "AddPizza" },new { httpMethod = new HttpMethodConstraint(new string[] { "POST" }) });
解决方法
您可以通过HTTP动词来限制您的路由,如下所示:
string[] allowedMethods = { "GET","POST" }; var methodConstraints = new HttpMethodConstraint(allowedMethods); Route reportRoute = new Route("pizza/{pizzaKey}",new MvcRouteHandler()); reportRoute.Constraints = new RouteValueDictionary { { "httpMethod",methodConstraints } }; routes.Add(reportRoute);
现在你可以拥有这两条路线,它们将受到动词的约束。