X-HTTP-Method-Override gives NotFound (404) on ASP.NET Web API

前端 未结 2 1065
长发绾君心
长发绾君心 2021-01-18 02:35

I am trying to implement HTTP method override following the steps described here. Basically, I am creating a DelegatingHandler, similar to the following, and adding it as a

2条回答
  •  后悔当初
    2021-01-18 03:13

    I think I'm having the same problem. It does look like the route constraints are checked before any message handlers.

    So I created a custom constraint that knows to check for an overridden HTTP method:

    class OverrideableHttpMethodConstraint : HttpMethodConstraint
    {
        public OverrideableHttpMethodConstraint(HttpMethod httpMethod) : base(httpMethod)
        {
        }
    
        protected override bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary values, HttpRouteDirection routeDirection)
        {
            IEnumerable headerValues;
            if (request.Method.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) && 
                request.Headers.TryGetValues("X-HTTP-Method-Override", out headerValues))
            {
                var method = headerValues.FirstOrDefault();
                if (method != null)
                {
                    request.Method = new HttpMethod(method);
                }
            }
    
            return base.Match(request, route, parameterName, values, routeDirection);
        }
    }
    

提交回复
热议问题