繁体   English   中英

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

[英]How to pass parameters to a WCF REST method using WinJS.xhr?

我试图将参数传递给我的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?;
    });

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

您的操作不起作用 - 因为您有多个参数,您需要将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
    });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM