首页 文章

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

提问于
浏览
1

所以我有一个像这样的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);
                }
            });
    }

这是基于我的web 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请求如下所示:

OPTIONS http://myserver:111/Api/V1/Customers/CreateCustomer/ HTTP / 1.1主机:MYSERVER:111连接:保活访问控制请求-方法:POST产地:http://localhost:6500的User-Agent: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 Accept:/ Referer:http://localhost:6500/Home/Replication?interval=1 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en; q = 0.8,烯GB; q = 0.6,它-IT; q = 0.4,它; q = 0.2

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

1 回答

  • 3

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

    "Access-Control-Allow-Origin", "*"
    
    "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"
    
    "Access-Control-Allow-Headers", "Content-Type, Accept"
    

    其次,如果你只需要某个控制器中的一个方法的CORS,你添加 Headers 的方式是可以的 . 但共同点是不对的 .

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

相关问题