首页 文章

Ajax POST到WCF Rest符合CORS的WebService抛出错误405

提问于
浏览
1

我'm doing some test over WCF REST WebServices and i'我坚持使用POST电话 . 我've created a webservice that exposes some test data about the good ol' Northwind DB,因为我希望从测试HTML页面本地使用它,因为我想测试CORS功能,我按照这些指令http://enable-cors.org/server_wcf.html使其符合CORS .

不幸的是,当我拨打POST电话时会出现问题 . 与GET调用(效果很好)不同,POST调用会抛出此错误:

POST error

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

这是我的jQuery Ajax post命令:

//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"设置为现有的 . 我遇到问题的web服务方法是对“http://localhost:3434/NorthwindService.svc/Customer/Create”方法的POST,所有其他方法都可以正常工作 . 这是我的方法 Contract 的预览:

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

提前致谢 .

2 回答

  • 1

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

    这就是为什么你得到HTTP响应405方法不允许(OPTIONS请求没有处理程序)

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

  • 1

    我没有't know what'继续,但感谢supertopi和他的链接,我做了正确的步骤,使其工作 . 不幸的是,实现这里讨论的所有事情How to handle Ajax JQUERY POST request with WCF self-host都没有用 . 即使创建一个新项目,我仍然继续获得"405 Method not allowed" . 在我的情况下唯一有效的是:

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

    2)在服务 Contract 中创建以下方法:

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

    3)实现它是空的 .

    public void GetOptions()
    {
    
    }
    

    这听起来很疯狂,但它确实有效 . 如果我删除GetOptions()操作 Contract ,我继续在我的客户端上获得405错误 . 如果我像supertopi的链接那样实现它(显然在删除了步骤1中创建的所有内容之后),它也不起作用 .

    希望能帮助到你 .

相关问题