所以我有一个像这样的 jquery ajax 请求:
function createLokiAccount(someurl) {
var d = {"Jurisdiction":17}
$.ajax({
type: "POST",
url:"http://myserver:111/Api/V1/Customers/CreateCustomer/",
data: JSON.stringify(d),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
}
这正在访问我的网络 API,基本上是:
[HttpPost]
public CreateCustomer.Response CreateCustomer(CreateCustomer.Request request)
{
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
...
当我在 Chrome 中调用它时,会得到:
OPTIONS http://myserver:111/Api/V1/Customers/CreateCustomer/ 405 (Method Not Allowed)
No 'Access-Control-Allow-Origin' header is present on the requested resource.
当我从 Fiddler 发出 POST 请求时,它应该在响应 header 中包含“Access-Control-Allow-Origin: *”,这表明 API 配置正确,但(来自 Fiddler)jquery 请求看起来像:
选项http://myserver:111/Api/V1/Customers/CreateCustomer/ HTTP/1.1 主机:我的服务器:111 连接:保持事件状态 访问控制请求方法:POST 来源:http://localhost:6500 用户代理:Mozilla/5.0(Windows NT 6.1;WOW64)AppleWebKit/537.36(KHTML,如 Gecko)Chrome/34.0.1847.116 Safari/537.36 访问控制请求 header :接受,内容类型 接受:/ 推荐人:http://localhost:6500/Home/Replication?interval=1 接受编码:gzip、deflate、sdch 接受语言:en-US,en;q=0.8,en-GB;q=0.6,it-IT;q=0.4,it;q=0.2
那么为什么我的 POST 请求变成了 OPTIONS 请求?
最佳答案
首先,您只添加一个 header ,但您至少需要三个 header :
"Access-Control-Allow-Origin", "*"
"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"
"Access-Control-Allow-Headers", "Content-Type, Accept"
其次,如果您仅需要某个 Controller 中的一种方法使用 CORS,那么添加 header 的方式就可以。但总的来说这是不对的。
带有 Web API 2 的 ASP.NET 5 提供 CORS library .
但是如果您使用 Web API,我可以提供解决方案(不是真正正确,但有效)。只需添加(在 Global.asax 中)到每个请求所需的 header
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
关于JQuery Ajax POST 到 Web API 返回 405 方法不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29813719/