我在使用jquery将一些json数据发布到我在WCF服务上的rest方法时遇到了一些麻烦.
在WCF方面,这是操作合同:
[OperationContract]
[WebInvoke(Method = "POST",
           BodyStyle = WebMessageBodyStyle.Bare,
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "PostSomething")]
MyResult PostSomething(MyRequest request);
双方MyResult并MyRequest标有所有必要DataContract和DataMember属性和服务暴露WebHttp端点.
在JQuery方面,这是我的函数调用:
var jsonStr = JSON.stringify(reqObj);
$.ajax({
    type: "POST",
    dataType: "json",
    url: "http://localhost/MyService/PostSomething",
    contentType: "application/json; charset=utf-8",
    data: jsonStr,
    success: function (html) {
        alert(html);
    }
});
这个请求永远不会到达我的方法(我每次都得到一个405方法不允许),并查看Charles的请求如下所示:
OPTIONS /MyService/PostSomething HTTP/1.1
Host: localhost
Cache-Control: max-age=0
Access-Control-Request-Method: POST
Origin: null
Access-Control-Request-Headers: Content-Type, Accept
Accept: */*
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 …