Web Services jQuery . AJAX ()POST请求在RESTful WCF上抛出405(不允许使用此方法)

e0bqpujr  于 2023-01-09  发布在  jQuery
关注(0)|答案(6)|浏览(182)

我正在向RESTFUL WCF服务应用程序发送发布请求。我能够通过Fiddler成功发送POST请求。
但是,当我通过jQuery AJAX 方法执行此操作时,该函数会向Chrome开发者控制台返回以下内容:

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

但在日志之后的一秒钟:

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

这告诉我jQuery正在发送一个失败的**OPTIONS**请求,然后发送一个返回预期数据的POST请求。
我的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             
});

我使用的是jQuery 2.0.2版。
任何有关此错误发生原因的帮助都将是很大的帮助。

ar5n3qh5

ar5n3qh51#

您的代码实际上尝试发出Cross-domain (CORS)请求,而不是普通的POST

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

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

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

  • 将首先向目标URL发送OPTION请求
  • 然后,仅当服务器对OPTION的响应包含adequate headers ( Access-Control-Allow-Origin is one of them)以允许CORS请求时,浏览才会执行调用(几乎与HTML页面位于同一域时的方式完全相同)。
  • 如果预期的标题没有出现,浏览器就会放弃(就像它对你做的那样)。
    **如何解决?**最简单的方法是在服务器上启用CORS(启用必要的头)。

如果您无法在服务器端访问它,则可以从其他位置镜像Web服务,然后在那里启用CORS。

bbuxkriu

bbuxkriu2#

您必须在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();
            }
        }
9jyewag0

9jyewag03#

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

@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);
    }
    ...
}
anauzrmj

anauzrmj4#

这对我很有效
Web.config中添加以下脚本

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="WebDAVModule"/>
  </modules>
  <handlers accessPolicy="Read, Execute, Script">
    <remove name="WebDAV" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />

    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
         verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
         type="System.Web.Handlers.TransferRequestHandler"
         preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
 </system.webServer>

另请参见路由配置.cs
变更
设置。自动重定向模式=重定向模式。永久;

设置。自动重定向模式=重定向模式。关闭;
希望对你或某人有帮助:)

cidc1ykv

cidc1ykv5#

对于相同的错误代码,我有相当不同的原因,我在这里分享,以帮助
我有如下的web API操作

public IHttpActionResult GetBooks (int id)

我更改了方法以接受两个参数category和author,因此我将参数更改如下,我还将属性[Httppost]

public IHttpActionResult GetBooks (int category, int author)

我还改变 AJAX 选项,如下面,在这一点上,我开始得到错误405方法不允许

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

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

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

7dl7o3gd6#

对于VScode用户-您是否通过vs code使用live-server?正常访问:)
jQuery . AJAX ()不适用于-

http://127.0.0.1:5500/index.html

它在里面工作!!-

http://192.168.29.10/index.php

相关问题