ASP MVC 3 - Jquery Ajax总是发送Options而不是Post

时间:2011-06-19 16:23:13

标签: jquery ajax http asp.net-mvc-3 rest

我有一个简单的javascript ajax请求:

$("#login-submit").button().click(function() {
                var ajaxOptions = {
                    url: "http://localhost:29097/authentication/",
                    type: "POST",
                    data: $("login-form").serialize(),
                    success: function(result) { $("body").html(result); }
                };
                $.ajax(ajaxOptions);
            });

但是每当我发送请求时,它总是发送一个OPTIONS请求,而不是指定的POST请求。在阅读之后,似乎可能会进入跨站点发布。我在我的MVC应用程序中添加了一个自定义操作过滤器,用于检查OPTION请求并使用“允许”标头进行响应,指定“GET,POST,PUT,DELETE”,尽管它似乎永远不会执行后续POST请求...我是在这里遗漏了什么?

请求(在Firefox,Chrome中尝试过):

OPTIONS http://localhost:29097/authentication/ HTTP/1.1
Host: localhost:29097
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with

回应:

HTTP/1.1 401 Unauthorized
Server: ASP.NET Development Server/10.0.0.0
Date: Sun, 19 Jun 2011 16:20:41 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Allow: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Max-Age: 1000
Access-Control-Allow-Headers: *
Access-Control-Allow-Origin: *
Cache-Control: private
Content-Length: 0
Connection: Close

我自己通过MVC发回401请求,因为它似乎是用来指示用户凭据无效的最佳标头。这个状态代码可能导致任何问题吗?

1 个答案:

答案 0 :(得分:5)

您正在使用实施Cross Origin Resource Sharing的浏览器。为了支持这一点,您的服务器需要使用Access-Control-Allow-Origin标头响应OPTIONS请求。