簡體   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