2013-04-02 33 views
0

我想传递参数给我使用REST传递数据的WCF。如何使用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?; 
    }); 

,但不知道如何在功能做或者如果我要通过我的参数提前...

回答

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