How to route GET and DELETE requests for the same url to different controller methods

僤鯓⒐⒋嵵緔 提交于 2019-11-28 22:54:15
womp

You can constrain your routes by HTTP verb like this:

  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);

Now you can have both routes, and they will be constrained by the verbs.

[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) { }

Womp's solution did not work for me.

This does:

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;
        }
    }
}

In case anyone else is having issues with having different routes based on request method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!