Call Page WebMethod from a Winforms Client using AJAX
My primary idea for this post was how to use the small and beauty JSON format for data transfer in a windows mobile application. For that I use the infrastructure of AJAX. I implement a Webmethod in a classic ASPX page.
<
script runat="server"><WebMethod()> _
<ScriptMethod()> _
Public Shared Function Nachladen1(ByVal contextKey As String) As String
Return "Hannes Preishuber"
End Function
</
script>For calling the Method form the page (or from a webservice) i use a Winforms application and the httpwebrequest class. Then i call the URL following the method name. The second part is to use a specific content type in header "application/json". To transfer complex data you have to build a json type. For my sample i used a simple string containing "test". The contextKey is a reserved word.
The result is in my sample also a string and can be passed to a textbox.
Private
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wRequest As HttpWebRequest = HttpWebRequest.Create("http://url/Default4.aspx/Nachladen1")wRequest.Method =
"POST"wRequest.ContentType =
"application/json; charset=utf-8"wRequest.Headers.Add(HttpRequestHeader.Pragma.ToString,
"no-cache") Using writer As Stream = wRequest.GetRequestStream Dim send As Stringsend =
"{""contextKey"":""test""}" Dim data As [Byte]() = Encoding.ASCII.GetBytes(send)writer.Write(data, 0, data.Length)
End Using Dim WResponse As HttpWebResponse = CType(wRequest.GetResponse, HttpWebResponse) Dim recieve As StreamReader = New StreamReader(WResponse.GetResponseStream()) Dim result As String = recieve.ReadToEnd.ToStringTextBox1.Text = result
End Sub
Small nice and sexy!