jQuery .ajax() POST 请求在 RESTful WCF 上抛出 405(不允许方法)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17333013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:50:33  来源:igfitidea点击:

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

jqueryweb-servicesrestpostwcf-rest

提问by Brandon Davis

I am sending a post request to a RESTFUL WCF service application. I am able to successfully send a POSTrequest through Fiddler.

我正在向 RESTFUL WCF 服务应用程序发送发布请求。我能够POST通过 Fiddler成功发送请求。

However when I do this through the jQuery Ajax method the function returns the following to the Chrome Developer Console:

但是,当我通过 jQuery Ajax 方法执行此操作时,该函数会向 Chrome 开发人员控制台返回以下内容:

OPTIONS http://www.example.com/testservice/service1.svc/GetData 405 (Method Not Allowed) jquery.min.js:6

But then a second after logs:

但是在记录后一秒钟:

Object {d: "You entered 10"} testpost.html:16

What this tells me is that jQuery is sending a OPTIONSrequest, which fails, and then sending a POSTrequest which returns the expected data.

这告诉我 jQuery 正在发送一个OPTIONS失败的请求,然后发送一个POST返回预期数据的请求。

My jQuery Code:

我的jQuery代码:

$.ajax() {        
type: "POST", //GET or POST or PUT or DELETE verb 
    url: "http://www.example.com/testservice/service1.svc/GetData", // Location of the service      
    data: '{"value":"10"}', //Data sent to server
    contentType:"application/json",
    dataType: "json", //Expected data format from server    
    processdata: false,
    success: function (msg) {//On Successfull service call   
        console.log(msg);
    },
    error: function (xhr) { console.log(xhr.responseText); } // When Service call fails             
});

I am using jQuery version 2.0.2.

我正在使用 jQuery 2.0.2 版。

Any help on why this error is occurring would be a great help.

关于为什么会发生此错误的任何帮助都会有很大帮助。

回答by acdcjunior

Your code is actually attempting to make a Cross-domain (CORS)request, not an ordinary POST.

您的代码实际上是在尝试发出跨域 (CORS)请求,而不是普通的POST.

That is: Modern browsers will only allow Ajax calls to services in the same domainas the HTML page.

也就是说:现代浏览器将只允许 Ajax 调用与 HTML 页面位于同一域中的服务。

Example:A page in http://www.example.com/myPage.htmlcan only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.

示例:页面中http://www.example.com/myPage.html只能直接请求 中的服务http://www.example.com,例如http://www.example.com/testservice/etc。如果服务在其他域中,浏览器将不会进行直接调用(如您所料)。相反,它会尝试发出 CORS 请求。

To put it shortly, to perform a CORS request, your browser:

简而言之,要执行 CORS 请求,您的浏览器:

  • Will first send an OPTIONrequest to the target URL
  • And then only ifthe server response to that OPTIONcontains the adequate headers (Access-Control-Allow-Originis one of them)to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
    • If the expected headers don't come, the browser simply gives up (like it did to you).
  • 会先向OPTION目标 URL发送请求
  • 然后只有当服务器响应OPTION包含足够的标头(Access-Control-Allow-Origin是其中之一)以允许 CORS 请求时,浏览才会执行调用(几乎与 HTML 页面位于同一域时的方式完全相同)。
    • 如果预期的标题没有出现,浏览器就会放弃(就像它对你所做的那样)。

How to solve it?The simplest way is to enable CORS (enable the necessary headers) on the server.

如何解决?最简单的方法是在服务器上启用 CORS(启用必要的标头)。

If you don't have server-side access to it, you can mirror the web service from somewhere else, and then enable CORS there.

如果您没有服务器端访问它,您可以从其他地方镜像 Web 服务,然后在那里启用 CORS。

回答by ali bencharda

You must add this code in global.aspx:

您必须在global.aspx 中添加此代码:

 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("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

回答by user4227302

You can create the required headers in a filter too.

您也可以在过滤器中创建所需的标题。

@WebFilter(urlPatterns="/rest/*")
public class AllowAccessFilter implements Filter {
    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("in AllowAccessFilter.doFilter");
        HttpServletRequest request = (HttpServletRequest)sRequest;
        HttpServletResponse response = (HttpServletResponse)sResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type"); 
        chain.doFilter(request, response);
    }
    ...
}

回答by sairfan

For same error code i had quite different reason, I'm sharing here to help

对于相同的错误代码,我有完全不同的原因,我在这里分享以提供帮助

I had web api action like below

我有如下的 web api 操作

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

我改变了接受两个参数类别和作者的方法,所以我改变了如下参数,我还把属性[Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

我还更改了如下所示的 ajax 选项,此时我开始收到错误 405 方法不允许

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

当我为 web api 操作参数创建类时,如下错误消失了

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)