Transferred from: http://www.cnblogs.com/SilenceTom/p/6697484.html
The calling interface encountered an error Response for preflight have invalid HTTP status code 405 , which was to use the Put method to submit the request interface. The Content-type is set to the APPLICATION/JSON,JS code as follows:
$.ajax ({ type: "PUT", URL: "Http://172.16.200.84:8977/Messages?sessionId=ee876bfbtest", Data:data, beforesend:function (XMLHttpRequest) { xmlhttprequest.setrequestheader ("Content-type", "Application/json "); }, success:function (data, textstatus) { alert (data); }});
Try to solve
The project uses the WEBAPI, according to the online comparison of the common method is directly in the project's webconfig configuration of the following nodes:
<system.webServer>
Of course, after the configuration is still not successful, and then try again or fail. is still the original error.
Keep trying.Later notice that the failed Request method is the options, strange, obviously is put request, how appeared the method for options request? Also add the following treatment to the Global.asax:
protected void Application_BeginRequest () { if (Request.Headers.AllKeys.Contains ("Origin") && Request.httpmethod = = "OPTIONS") { response.end (); }}
ReasonTry again and succeed. But look at the record, there will be two requests, one is the options request returns 200 succeeds, one is own put request, returns 200 succeeds. So what exactly is the options request? Baidu got a bit of the answer:
Preflighted requests (pre-inspection request)
Preflighted Requests is a transparent server authentication mechanism in Cors. The preflight request first needs to send an HTTP OPTIONS request header to the resource of another domain name in order to determine whether the actual sent request is secure.
The following 2 scenarios require a preflight:
1, simple request, such as the use of Content-type for Application/xml or text/xml POST request;
2, set the custom head, such as X-json, X-mengxianhui and so on.
So, when JS launched the put request, the head set Xmlhttprequest.setrequestheader ("Content-type", "Application/json"), so the request will be an extra options , if the head is removed, no more requests will be made.
What is CorsCORS processAddOf course, for security reasons, you can not configure Web. config, but instead define a actionalloworiginattribute, inherit from ActionFilterAttribute, and label the interfaces that require cross-domain access, Mainly in the header add the following content:
Response. AddHeader ("Access-control-allow-origin", "*"); response. AddHeader ("Access-control-allow-methods", "put,get,post,options"); response. AddHeader ("Access-control-allow-headers", "X-requested-with, Content-type, x-file-name");
Goto Js Cross-domain cors error Response for preflight have invalid HTTP status code 405