JQuery Ajax POST 到 Web API 返回 405 方法不允许

JQuery Ajax POST to Web API returning 405 Method Not Allowed

所以我有一个 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 主持人:myserver:111 连接:keep-alive Access-Control-Request-Method: POST 来源:http://localhost:6500 User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Access-Control-Request-Headers:接受,content-type 接受:/ 推荐人:http://localhost:6500/Home/Replication?interval=1 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,en-GB;q=0.6,it-IT;q=0.4,it;q=0.2

为什么我的 POST 请求变成了 OPTIONS 请求?

首先,您只添加了一个 header,但您至少需要添加三个:

"Access-Control-Allow-Origin", "*"

"Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"

"Access-Control-Allow-Headers", "Content-Type, Accept"

其次,如果您只需要为某个控制器中的一种方法使用 CORS,那么您添加 headers 的方式就可以了。但总的来说这是不对的。

ASP.NET 5 个网络 API 2 个报价 CORS library.

但如果您使用的是 Web API,我可以提供解决方案(不是很合适,但可以)。只需将(在 Global.asax 中)添加到所需的每个请求 headers

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();
    }

}