0

我正在尝试将复杂对象上传到我的 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");
    }
});
4

1 回答 1

0

默认情况下,将使用该格式$.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"); 
    } 
}); 

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

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

于 2012-10-11T17:33:50.837 回答