我有一个在我的本地 IIS 实例上运行的 ASP.NET Web API 应用程序。Web 应用程序配置了 CORS。我调用的 Web API 方法如下所示:
[POST("/API/{foo}/{bar}")]
public String DoSomething(String foo, String bar)
{
return "Hello, World!";
}
客户端,我正在运行以下请求:
$.ajax({
url: "http://machine/API/Foo/Bar",
type: "POST",
success: function (data) {
console.log("Success: " + data);
},
error: function (xhr, status, message) {
console.log("Failure: " + status + ", " + message);
}
});
Firefox 15.0.1 中相应的控制台日志内容如下:
test.html (line 38)
POST http://machine/API/Foo/Bar
200 OK
112ms
jquery-1.7.2.js (line 8240)
Success: "Hello, World!"
当我访问我的本地 IIS 服务器以及让它访问 Visual Studio 中 IIS Express 开发实例的相应 URL 时,这可以完美地工作。
当我添加单个请求标头时,对我的本地 IIS 服务器发出以下请求时会失败:
$.ajax({
url: "http://machine/API/Foo/Bar",
type: "POST",
onBeforeSend: function (xhr, settings) {
xhr.setRequestHeader("A", "B");
},
success: function (data) {
console.log("Success: " + data);
},
error: function (xhr, status, message) {
console.log("Failure: " + status + ", " + message);
}
});
我看到的非常冗长的日志消息是:
Failure: error,
POST
在 Visual Studio 中针对 IIS Express 开发实例发出相同的请求时成功。
在 Fiddler 中,无论我的目标是完整的 IIS 服务器还是 Visual Studio 中的 IIS Express,前两个请求都会顺利通过:
// Request
POST http://machine/Foo/Bar HTTP/1.1
Host: machine
Content-Length: 0
// Response
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 38
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 09 Oct 2012 20:16:29 GMT
"Hello, World!"
这些排列{With Headers, Without Headers} x {Full IIS, IIS Express}
都在 Fiddler 中产生相同的输出。
简而言之:为什么设置请求标头会导致 AJAX 调用对我的本地完全成熟的 IIS 实例失败?
此外,为什么我的请求在 Fiddler 中成功,但在我的 Javascript 代码中却没有?如果我无法在正确的 IIS 实例中设置请求标头,这将是一个严重的交易破坏者。