使用JSON将数据传递到ASP.NET Webservice

时间:2010-06-22 06:09:13

标签: asp.net vb.net json web-services

我已经成功地从JSON格式的ASP.Net webservice返回数据(使用不需要参数的服务方法),但是在进行需要参数的webservice调用时却很困难。

web服务:

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function TestWebService(ByVal Description As String) As Stock
    Dim res As New Stock(Guid.NewGuid, Description)
    Return res
End Function

对象:

Public Class Stock

    Public Sub New()
    End Sub

    Public Sub New(ByVal StockID As Guid, ByVal Description As String)
        Me._StockID = StockID
        Me._Description = Description
    End Sub


    Public Property StockID As Guid
    Public Property Description As String

End Class

使用Javascript:

client = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
client.onreadystatechange = DataReturnedFromHttpRequest;
client.open("GET", "/MyWebService.asmx/TestWebService?" + JSON.stringify({"Description":["Test"]}), true); 
client.setRequestHeader("Content-Type", "application/json");
client.send(null);

响应:

{"Message":"Invalid web service call, missing value for parameter: \u0027Description\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}

我理解错误,但似乎无法确定如何正确格式化我的请求。

1 个答案:

答案 0 :(得分:1)

终于明白了...所以对于任何好奇的人来说,答案都是微不足道的。

get请求必须采用以下格式

/MyWebService.asmx/MyWebserviceMethod?Param1=%22ParamValue1%22&Param2=%22ParamValue2

然后它就像一个魅力。