2010-01-27 3 views
23

다음은 내 경로입니다. Global.asax동일한 URL에 대한 GET 및 DELETE 요청을 다른 컨트롤러 메서드로 라우팅하는 방법

 routes.MapRoute("PizzaGet", "pizza/{pizzaKey}", new { controller = "Pizza", action = "GetPizzaById" }); 
    routes.MapRoute("DeletePizza", "pizza/{pizzaKey}", new { controller = "Pizza", action = "DeletePizza" });  

다음은 내 컨트롤러 메소드입니다.

[AcceptVerbs(HttpVerbs.Get)] 
public ActionResult GetPizzaById(long pizzaKey) 

[AcceptVerbs(HttpVerbs.Delete)] 
public ActionResult DeletePizza(long pizzaKey) 

GET을 수행하면 개체가 반환되지만 삭제하면 404가됩니다. 이게 효과가있는 것처럼 보이지만 그렇지 않습니다.

그러면 두 경로를 전환하면 DELETE를 수행 할 수 있지만 GET에서 404를 얻습니다.

이제 정말 아름답습니다. 감사합니다

routes.MapRoute("Pizza-GET","pizza/{pizzaKey}", 
       new { controller = "Pizza", action = "GetPizza"}, 
       new { httpMethod = new HttpMethodConstraint(new string[]{"GET"})}); 

      routes.MapRoute("Pizza-UPDATE", "pizza/{pizzaKey}", 
       new { controller = "Pizza", action = "UpdatePizza" }, 
       new { httpMethod = new HttpMethodConstraint(new string[] { "PUT" }) }); 

      routes.MapRoute("Pizza-DELETE", "pizza/{pizzaKey}", 
       new { controller = "Pizza", action = "DeletePizza" }, 
       new { httpMethod = new HttpMethodConstraint(new string[] { "DELETE" }) }); 

      routes.MapRoute("Pizza-ADD", "pizza/", 
       new { controller = "Pizza", action = "AddPizza" }, 
       new { httpMethod = new HttpMethodConstraint(new string[] { "POST" }) }); 

답변

19

이 같은 HTTP 동사하여 경로를 제한 할 수 있습니다.

+1

새로운 anwser를 주셔서 감사합니다 .. 나는 또한 이것을 발견 http://arcware.net/adding-httpmethodconstraint-to-asp-net-mvc-routes/ –

18
[ActionName("Pizza"), HttpPost] 
public ActionResult Pizza_Post(int theParameter) { } 

[ActionName("Pizza"), HttpGet] 
public ActionResult Pizza_Get(int theParameter) { } 

[ActionName("Pizza"), HttpHut] 
public ActionResult Pizza_Hut(int theParameter) { } 
0

Womp의 해결책이 저에게 효과적이지 않았습니다.

이 수행합니다

namespace ... 
{ 
    public class ... : ... 
    { 
     public override void ...(...) 
     { 
      context.MapRoute(
       "forSpecificRequestMethod", 
       "...{rctrl}/{ract}/{id}", 
       new { controller = "controller", action = "action", id = UrlParameter.Optional }, 
       new RouteValueDictionary(new { httpMethod = new MethodRouteConstraint("REQUEST_VERB_HERE") }), 
       new[] { "namespace" } 
      ); 

      context.MapRoute(
       "default", 
       "...{controller}/{action}/{id}", 
       new { action = "Index", id = UrlParameter.Optional }, 
       new[] { "namespace" } 
      ); 
     } 
    } 

    internal class MethodRouteConstraint : IRouteConstraint 
    { 
     protected string method; 
     public MethodRouteConstraint(string method) 
     { 
      this.method = method; 
     } 
     public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) 
     { 
      return httpContext.Request.HttpMethod == method; 
     } 
    } 
} 

경우 다른 사람에 요청 방법에 따라 서로 다른 경로를 갖는 문제가있다.

관련 문제