WCF无法反序列化JSON请求

WCF无法反序列化JSON请求,json,wcf,Json,Wcf,我试图编写一个WCF服务来响应ajax请求,但当它尝试反序列化时,我遇到了一个奇怪的错误 以下是jQuery: $.ajax({ type: 'POST', url: 'http://localhost:4385/Service.svc/MyMethod', dataType: 'json', contentType: 'application/json', data: JSON.stringify({folder:"test", name:"test"

我试图编写一个WCF服务来响应ajax请求,但当它尝试反序列化时,我遇到了一个奇怪的错误

以下是jQuery:

$.ajax({
    type: 'POST', 
    url: 'http://localhost:4385/Service.svc/MyMethod',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({folder:"test", name:"test"})
});
以下是WCF服务定义:

[OperationContract]
[WebInvoke(UriTemplate = "/MyMethod", 
    Method = "*", //Need to accept POST and OPTIONS
    BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)]
string[] MyMethod(string folder, string name);
我得到一个
SerializationException
说:“OperationFormatter无法反序列化消息中的任何信息,因为消息为空(IsEmpty=true)。”

它出现在指令
00000108 mov dword ptr[ebp-18h],0的方法
System.ServiceModel.Dispatcher.PrimitiveOperationFormatter.DeserializeRequest

我不知道我做错了什么,但它拒绝为我工作。我整天都在为此奋斗。有什么想法吗?

明白了——答案就在我代码中唯一的注释中。我需要接受POST和选项(对于CORS)。选项请求是先来的,当然选项请求没有附加任何数据。这就是导致解析异常的原因;这篇文章根本就没发生过

解决方法:将POST和选项分成两个不同的方法,使用相同的UriTemplate,但使用不同的C#name(WCF需要这样做)

这实际上清理了一点代码,因为您不必在所有函数中乱丢东西

if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS") {
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, POST");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, User-Agent");
    return new string[0];
} else if (WebOperationContext.Current.IncomingRequest.Method == "POST") { ... }
if (WebOperationContext.Current.IncomingRequest.Method == "OPTIONS") {
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "OPTIONS, POST");
    WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, User-Agent");
    return new string[0];
} else if (WebOperationContext.Current.IncomingRequest.Method == "POST") { ... }