2012-09-29 33 views
2

我的WebMethod看起來是這樣的:爲什麼我無法使用GET將參數發送到WebMethod?

[WebMethod] 
[ScriptMethod(ResponseFormat=ResponseFormat.Json, UseHttpGet=true)] 
public List<Person> HelloWorld(string hello) 
{ 
    List<Person> persons = new List<Person> 
    { 
     new Person("Sarfaraz", DateTime.Now), 
     new Person("Nawaz", DateTime.Now), 
     new Person("Manas", DateTime.Now) 
    }; 
    return persons; 
} 

而且我試圖調用使用jQuery這個方法爲:

var params={hello:"sarfaraz"}; //params to be passed to the WebMethod 
$.ajax 
({ 
    type: "GET", //have to use GET method 
    cache: false, 
    data: JSON.stringify(params), 
    contentType: "application/json; charset=utf-8", 
    dataType: 'json', 
    url: "http://localhost:51519/CommentProviderService.asmx/HelloWorld", 
    processData: true, 
    success: onSuccess, 
    error: onError  //it gets called! 
}); 

但它不工作。而不是調用onSuccess回調,它調用onError中,我使用alert爲:

alert(response.status + " | " + response.statusText + " | " + response.responseText + " | " + response.responseXML); 

它打印此:

500 |內部服務器錯誤| {「Message」:「無效的Web服務調用, 缺少參數:\ u0027hello \ u0027的值。」, 「堆棧跟蹤」:」在 System.Web.Script.Services.WebServiceMethodData.CallMethod(對象 目標,IDictionary的2 parameters)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary 2個參數)\ r \ n在 System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext的 上下文中,WebServiceMethodData methodData,IDictionary`2 rawParams個)\ r \ n 在 System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext的 上下文,WebServiceMethodData methodData)」, 「ExceptionType」: 「System.InvalidOperationException」} | undefined

我不明白爲什麼我得到這個錯誤。

如果我更改jQuery調用使用POST方法和使UseHttpGet=false,那麼它的工作很好。但我希望它能與GET一起工作。什麼需要解決?

+0

嘗試.asmx/HelloWorld?你好= sarfaraz – sri

回答

1

HTTP GET期望參數全部在URL中編碼。

問題是您正在對您的有效負載執行JSON.stringifyjQuery.ajax實際上只是尋找簡單的字典,它可以變成一系列查詢字符串參數。

所以,如果你有一個這樣的對象:

{ name: "value" } 

jQuery將它添加到您的網址是這樣結尾:

?name=value 

使用Firebug,Chrome開發者工具,或IE開發者工具來檢查傳出的URL,我懷疑你會看到它是ASP.Net無法翻譯的格式。

+0

現在,我試着用'{你好:'sarfaraz'}',我得到這個錯誤:'500 |內部服務器錯誤| {「消息」:「無效的JSON基元:sarfaraz。」,「StackTrace」:「在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()....' – Nawaz

+0

@Nawaz - 嘗試更改您的數據參數看起來像這個:'data:{「hello」:「sarfaraz」}' – Josh

+0

仍然是同樣的錯誤。「無效的JSON原語:sarfaraz [012]' – Nawaz

0

要在GET的$就要求,您必須設置您的數據params="hello=sarfaraz"

所以完整的代碼片段可以簡單地

var params="hello=sarfaraz"; //params to be passed to the WebMethod 
$.ajax 
({ 
    type: "GET", //have to use GET method 
    cache: false, 
    data: params, 
    dataType: 'json', 
    url: "http://localhost:51519/CommentProviderService.asmx/HelloWorld", 
    success: onSuccess, 
    error: onError //it gets called! 
}); 

希望幫助!

相關問題