我正在尝试编写一个 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"})
});
Run Code Online (Sandbox Code Playgroud)
这是 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);
Run Code Online (Sandbox Code Playgroud)
我得到一个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();
Run Code Online (Sandbox Code Playgroud)
这实际上清理了一些代码,因为你不必用
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") { ... }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4155 次 |
| 最近记录: |