我遇到了一些问题,无法让jquery将一些json数据发布到我的WCF服务上的rest方法。
在WCF方面,这是操作合同:
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "PostSomething")]
MyResult PostSomething(MyRequest request);
我使用了具有所有必要的 DataContract
和 DataMember
属性标记的 MyResult
和 MyRequest
, 并且服务正在公开 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 Method Not Allowed),在查看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 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
关于这个问题有几点很奇怪:
- 方法应该是OPTIONS而不是POST
- 内容类型(在另一个选项卡中)显示为
text/html; charset=UTF-8
而不是 JSON - 无法看到 JSON 数据
但是,如果我修改 Charles 中的请求头使其类似于此处的解决方案,那么一切都能正常工作:
POST /MyService/PostSomething HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: localhost
Content-Length: 152
{"Id":"", "Name":"testspot","Description":"test" }
从查看教程和其他在这里的问题中,其他人已经成功地将 JQuery 发送到 WCF REST 方法,就像这样,而我对我在这里做错了什么感到困惑...
哦,为了提供一些背景,这是一个 WCF 4 服务,并且我正在使用 JQuery 1.4.4。
谢谢,
更新:
经过更多阅读和感谢 Darrel 指向跨域规范,我通过对服务接口进行一些小改动,取得了一些进展:
[OperationContract]
[WebInvoke(Method = "*",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "PostSomething")]
MyResult PostSomething(MyRequest request);
在实现中,我需要检查传入的请求是否为OPTIONS,如果是,则返回一些头信息而不是执行预期的工作:
if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS")
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
return null;
}
这个方法被调用了两次,第一次服务器返回null但向客户端添加了一些头部信息,然后使用POST作为方法进行实际请求,服务器继续正常处理该请求。