Is it possible to implement X-HTTP-Method-Override in ASP.NET MVC?

后端 未结 8 1761
遥遥无期
遥遥无期 2020-12-18 08:02

I\'m implementing a prototype of a RESTful API using ASP.NET MVC and apart from the odd bug here and there I\'ve achieve all the requirements I set out at the start, apart f

8条回答
  •  青春惊慌失措
    2020-12-18 08:47

    I'm surprised that this hasn't been mentioned yet, but ASP.NET MVC natively supports X-HTTP-Method-Override and has been doing so from at least version 2. There's no need to write custom code to handle this.

    It work in the following way:

    Inside AcceptVerbsAttribute (also proxied by [HttpPut], [HttpPost], etc), there's an IsValidForRequest method. Inside that method, it checks with Request.GetHttpMethodOverride(), which returns the proper overriden HTTP method with the following conditions:

    • Overriding is only supported in POST requests. All others are ignored.
    • If the X-HTTP-Method-Override value is GET or POST, it's ignored. This makes sense, as you'd never need to override with these values.
    • It looks for X-HTTP-Method-Override in the following places in this priority: 1) HTTP Header 2) Form Body 3) Query String

    If you're really curious, here's how GetHttpMethodOverride() looks (from MVC 3's source code):

    public static class HttpRequestExtensions {
        internal const string XHttpMethodOverrideKey = "X-HTTP-Method-Override";
    
        public static string GetHttpMethodOverride(this HttpRequestBase request) {
            if (request == null) {
                throw new ArgumentNullException("request");
            }
    
            string incomingVerb = request.HttpMethod;
    
            if (!String.Equals(incomingVerb, "POST", StringComparison.OrdinalIgnoreCase)) {
                return incomingVerb;
            }
    
            string verbOverride = null;
            string headerOverrideValue = request.Headers[XHttpMethodOverrideKey];
            if (!String.IsNullOrEmpty(headerOverrideValue)) {
                verbOverride = headerOverrideValue;
            }
            else {
                string formOverrideValue = request.Form[XHttpMethodOverrideKey];
                if (!String.IsNullOrEmpty(formOverrideValue)) {
                    verbOverride = formOverrideValue;
                }
                else {
                    string queryStringOverrideValue = request.QueryString[XHttpMethodOverrideKey];
                    if (!String.IsNullOrEmpty(queryStringOverrideValue)) {
                        verbOverride = queryStringOverrideValue;
                    }
                }
            }
            if (verbOverride != null) {
                if (!String.Equals(verbOverride, "GET", StringComparison.OrdinalIgnoreCase) &&
                    !String.Equals(verbOverride, "POST", StringComparison.OrdinalIgnoreCase)) {
                    incomingVerb = verbOverride;
                }
            }
            return incomingVerb;
        }
    }
    

提交回复
热议问题