2013-04-02 36 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 
    });