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

时间:2015-04-23 04:30:57

标签: jquery ajax cors asp.net-web-api

所以我有一个像这样的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请求时,它在响应头中包含“Access-Control-Allow-Origin:*”,这表明API已正确配置,而(来自Fiddler)jquery请求看起来像:

选项http://myserver:111/Api/V1/Customers/CreateCustomer/ HTTP / 1.1 主持人:myserver: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 Access-Control-Request-Headers:accept,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请求?

1 个答案:

答案 0 :(得分:3)

首先,您只需添加一个标题,但至少需要其中三个标题:

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

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

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

其次,如果您在某个控制器中只需要一个方法的CORS,那么您添加标题的方式是可以的。但总的来说,这是不对的。

使用Web API 2的ASP.NET 5提供了CORS library

但是,如果你正在使用Web API,我可以提供解决方案(不是真正合适的,但有效)。只需将(在Global.asax中)添加到每个请求标题

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

}