预检的响应在Angular Js1和Webapi 2上具有无效的HTTP状态代码405

时间:2017-07-28 10:35:27

标签: angularjs cors asp.net-web-api2 angular-resource preflight

错误:

OPTIONS http://localhost:8080//api/home/GetText 405 (Method Not Allowed)

http://localhost:8080//api/home/GetText. Response for preflight has invalid HTTP status code 405
angular.js:14362 Error: Error getting home/GetText data from the database! 
Headers:

响应标题:

Access-Control-Allow-Credentials:false
Access-Control-Allow-Headers:gid,Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:GET
Content-Length:76
Content-Type:application/json; charset=utf-8
Date:Fri, 28 Jul 2017 10:30:06 GMT
Server:Microsoft-IIS/10.0
X-Powered-By:ASP.NET

请求标题:

Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:authorization,gid
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://evil.com/
Pragma:no-cache
Referer:http://localhost:1852/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36

请注意,我使用Angular Js作为客户端,使用Webapi作为服务器端。我正在通过$ resource service执行xhr请求。

3 个答案:

答案 0 :(得分:1)

这是因为您的后端API不支持您的路由OPTIONS请求(特别是/api/home/GetText此路由)。 AngularJS通常通过在发出实际内容请求之前发出OPTIONS请求来检查CORS请求。

您需要在后端启用对OPTIONS请求的支持,并从那里返回适当的标头+良好的HTTP状态(200-299)。

答案 1 :(得分:1)

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "gid, filename, Origin, X - Requested - With, Content - Type, Accept, Authorization");
            HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "X-filename");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }

这解决了上述问题。

答案 2 :(得分:0)

表示您尝试使用错误的HTTP VERBS从FRONT END到BACK END调用方法(例如,POST的PUT INSTEAD)

仔细检查