如何使用WinJS.xhr将参数传递给WCF REST方法?

时间:2013-04-02 16:55:57

标签: c# wcf rest winjs

我正在尝试将参数传递给使用REST传递数据的WCF。

我方法的定义是:

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]
void newUserAndImageEntry(byte[] pArrayImage, string pContentType, string pUserName, string pFileName);

我正在尝试的是:

WinJS.xhr({ url: "http://localhost:9814/Student.svc/newUserAndImageEntry" })
    .then(function (r ) {
        DO WHAT?;
    });

但是不知道该怎么做,或者我必须提前传递我的参数..

1 个答案:

答案 0 :(得分:2)

您的操作不起作用 - 因为您有多个参数,因此需要在您的方案中将BodyStyle属性定义为Wrapped(或WrappedRequest - 该操作没有返回值,没关系):

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void newUserAndImageEntry(byte[] pArrayImage, string pContentType,
    string pUserName, string pFileName);

另一个问题是字节数​​组可能不是从JavaScript接收数据的好类型 - 它将作为数字数组接收,效率不高。在客户端上进行一些预处理 - 例如,将字节编码为base64,将为您提供更小的有效负载

[OperationContract]
[WebInvoke(RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.WrappedRequest)]
void newUserAndImageEntry(string pArrayImageAsBase64, string pContentType,
    string pUserName, string pFileName);

现在对于客户端:您需要在您传递的对象的data字段中传递参数作为参数。类似下面的代码。有关通话的详细信息,请查看WinJS.xhr documentation

var arrayImage = getArrayImage();
var arrayImageBase64 = convertToBase64(arrayImage);
var contentType = 'image/jpeg';
var userName = 'johndoe';
var fileName = 'balls.jpg';
var data = {
    pArrayImageAsBase64: arrayImageBase64,
    pContentType: contentType,
    pUserName: userName,
    pFileName: fileName
};
var xhrOptions = {
    url: "http://localhost:9814/Student.svc/newUserAndImageEntry",
    headers: { "Content-Type": "application/json" },
    data: JSON.stringify(data)
};
WinJS.xhr(xhrOptions).done(
    function (req) {
        // Call completed, find more info on the parameter
    }, function (req) {
        // An error occurred, find more info on the parameter
    });
相关问题