【问题标题】:Ajax POST to WCF Rest CORS-compliant WebService throws error 405Ajax POST 到 WCF Rest CORS 兼容的 WebService 引发错误 405
【发布时间】:2015-05-01 08:32:53
【问题描述】:

我正在对 WCF REST WebServices 进行一些测试,但我遇到了 POST 调用。 我创建了一个 web 服务,它公开了一些关于良好的 ol' Northwind DB 的测试数据,因为我希望从测试 HTML 页面在本地使用它,并且因为我想测试 CORS 功能,所以我通过遵循这些使其符合 CORS指令http://enable-cors.org/server_wcf.html

不幸的是,当我进行 POST 调用时出现问题。 不像 GET 调用(效果很好),POST 调用会抛出这个错误:

这是什么鬼?似乎“Access-Control-Allow-Origin”标头未在客户端正确管理,因为在我的 EnableCrossOriginResourceSharingBehavior WCF 类中,方法“ApplyDispatchBehavior”(它过滤了到达请求的“Access-Control-Allow-Origin”标头) 在我进行 POST 调用时被命中,但随后 Ajax 调用失败。

这是我的 jQuery Ajax 发布命令:

       //Create new object
        var item = {
            "CustomerId": "0",
            "CompanyName": "prova"
        };

        //Push object
        $.ajax({
            type: "POST",
            url: 'http://localhost:3434/NorthwindService.svc/Customer/Create',
            crossDomain: true,
            headers: {'Access-Control-Allow-Origin' : '*'},
            data: JSON.stringify(item),
            success: function (data) {
                alert('ok!');
            },
            contentType: 'application/json; charset=utf-8',
            dataType: 'json'
        });

This 是我的 WCF 服务 Visual Studio 2013 项目。 要对其进行测试,您只需将 web.config 中的“NorthwindConnectionString”设置为现有的。我遇到问题的网络服务方法是“http://localhost:3434/NorthwindService.svc/Customer/Create”方法的 POST,所有其他方法都可以正常工作。 这是我的方法契约的预览:

 [OperationContract]
 [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "Customer/Create", BodyStyle=WebMessageBodyStyle.WrappedRequest)]
 void NewCustomer(CustomerDTO customer);

提前致谢。

【问题讨论】:

    标签: ajax wcf rest post http-status-code-405


    【解决方案1】:

    我不知道发生了什么,但感谢 supertopi 和他的链接,我采取了正确的步骤使其正常工作。不幸的是,实现这里@9​​87654321@ 中讨论的所有事情都不起作用。即使创建一个新项目,我也继续得到“405 Method not allowed”。 在我的情况下唯一有效的是:

    1) 实现 CustomHeaderMessageInspector 和 EnableCrossOriginResourceSharingBehavior 类并编辑 web.config,如 http://enable-cors.org/server_wcf.html 中公开的那样。

    2) 在服务契约中创建如下方法:

    [OperationContract]
    [WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
     void GetOptions();
    

    3) 空实现。

    public void GetOptions()
    {
    
    }
    

    这听起来很疯狂,但它确实有效。 如果我删除 GetOptions() 操作合同,我的客户端继续收到 405 错误。如果我按照 supertopi 的链接所示实现它(显然在删除步骤 1 中创建的所有内容之后),它也不起作用。

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      您的 HTTP 请求方法定义为 OPTIONS 而不是 POST

      这就是为什么你得到 HTTP Response 405 Method not Allowed (no handler for OPTIONS request)

      将 jQuery ajax 构造函数中的类型参数更改为"POST" 并将请求路由到正确的处理程序。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-24
      • 2016-11-11
      • 2017-05-06
      • 2011-12-10
      • 2015-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多