从JQuery将复杂对象上载到WCF REST服务

我正在尝试将复杂对象上传到我的WCF REST服务。 我这样做是因为它似乎是同时将Stream类型对象和其他参数上传到端点的最简单方法。

服务:

[OperationContract] [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Upload")] public string upload(UploadObject uploadObject) { return uploadObject.stream.ToString() + " " + uploadObject.guid; } [DataContract] public class UploadObject { [DataMember] public Stream stream { get; set; } [DataMember] public string guid { get; set; } } 

JQuery的

 var guid = getParameterByName("guid"); //<--gets value from query string parameter var file = $('#btnUpload').val(); //<--value from a file input box var uploadObject = { stream: file, guid: guid }; $.ajax({ type: "POST", contentType: "application/json", url: "localhost/service/Upload", data: uploadObject, datatype: "jsonp", processData : false, success: function(data){ alert(data); }, error: function (xhr, status, error) { alert("fail"); } }); 

默认情况下, $.ajax将使用application/x-www-form-urlencoded格式对对象进行编码。 你说内容类型是JSON,所以你也应该使用那种格式编码对象(使用JSON.stringify应该这样做):

 var guid = getParameterByName("guid"); //<--gets value from query string parameter var file = $('#btnUpload').val(); //<--value from a file input box var uploadObject = { stream: file, guid: guid }; $.ajax({ type: "POST", contentType: "application/json", url: "localhost/service/Upload", data: JSON.stringify(uploadObject), processData : false, success: function(data){ alert(data); }, error: function (xhr, status, error) { alert("fail"); } }); 

此外,您不能为POST请求指定dataType: "jsonp" 。 JSONP仅适用于GET请求。

合同还有一个问题:您不能将Stream作为数据合同的一部分; Stream是一个抽象类,WCF序列化程序不知道如何反序列化为抽象类。 JS代码中“文件”的类型究竟是什么? 如果是文件内容,是否存储在字符串中? 如果是这样,请在合同中使用字符串作为数据类型。