Wednesday, March 5, 2008

Using Session State in a Webservice AND calling from a Windows Form

So setting up a WebMethod to use Session is not that difficult:

<WebMethod(EnableSession:=True)> _
Public Function HelloWorld() As String

If Session("FirstCall") Is Nothing Then
Session("FirstCall") = Now
End If

Return Session("FirstCall")
End Function

And calling this from a webform is not a problem since the browser can handle session information in a cookie etc. However it gets just a little tricky when you call it from a windows form because it has no idea about cookies. So you have to take care of it in the call like this:

Private Cookies As System.Net.CookieContainer

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click

Dim proxy As New localhost.Service()
' Set the Cookie Container on the proxy
If Cookies Is Nothing Then
Cookies = New System.Net.CookieContainer()
End If
proxy.CookieContainer = Cookies

End Sub

A great explanation can be found here:

No comments: