WCF无法反序列化JSON请求

问题描述:

我想写一个WCF服务来响应Ajax请求,但是当它试图反序列化时,我收到了一个奇怪的错误。WCF无法反序列化JSON请求

这里是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)“。

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

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

明白了 - 答案在我的代码中唯一的评论中正盯着我。我需要接受POST和OPTIONS(用于CORS)。 OPTIONS请求首先出现,当然OPTIONS请求没有附加数据。 是导致解析异常的原因;而POST甚至从未发生过。

解决方法:将POST和OPTIONS分离为两个单独的方法,具有相同的UriTemplate,但具有不同的C#名称(WCF需要此方法)。

[OperationContract] 
[WebInvoke(UriTemplate = "/MyMethod", 
    Method = "POST", 
    BodyStyle = WebMessageBodyStyle.WrappedRequest, 
    RequestFormat = WebMessageFormat.Json, 
    ResponseFormat = WebMessageFormat.Json)] 
string[] MyMethod(string folder, string name); 

[OperationContract] 
[WebInvoke(UriTemplate = "/MyMethod", Method = "OPTIONS")] 
void MyMethodAllowCors(); 

这实际上清理代码一点,因为你不必垃圾所有的功能与

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") { ... }