asp.net-mvc – 如何将相同URL的GET和DELETE请求路由到不同的控制器方法

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何将相同URL的GET和DELETE请求路由到不同的控制器方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我在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);

现在你可以拥有这两条路线,它们将受到动词的约束。

原文链接:/aspnet/253663.html

猜你在找的asp.Net相关文章