2012-09-29 57 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! 
}); 

希望帮助!

相关问题