2012-04-29 112 views
4

我想寫一個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

我不知道我做錯了什麼,但它拒絕爲我工作。一整天都在戰鬥。有任何想法嗎?

回答

2

明白了 - 答案在我的代碼中唯一的評論中正盯着我。我需要接受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") { ... }