0

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

我的方法的定义是:

[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?;
    });

但是不知道在函数中要做什么,或者我是否必须提前传递我的参数..

4

1 回答 1

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 文档以获取有关该调用的更多详细信息。

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
    });
于 2013-04-02T17:52:19.023 回答