SUMMARY
This step-by-step article describes how you can use the
System.Net.CookieContainer class with sessions or cookies when you use a Web service in an
application.
Although Web services are inherently stateless, you may
use session objects to maintain stateful communication between a client
application and a server application. To enable stateful communication between
the Web client and the Web service, you may use the
CookieContainer object with each message that is sent to the Web service from the
client application. You may consume a stateful Web service in a state-enabled
client application.
back to the
topCreate a Web Service Application
- Run Microsoft Visual Studio .NET. Create a new ASP.NET Web
service project by using Visual Basic .NET.
By default, Service1.asmx
is created. - Name the project MyWebService.
- On the Build menu, click Build
Solution.
back to the
topEnable Session Support on the Server
By default, ASP.NET session support for each Web Service
method is turned off. You must explicitly enable session support for each Web
Service method that requires a session state. To enable the session support,
add the
EnableSession property to the
WebMethod attribute as follows:
- In Solution Explorer, right-click
Service1.asmx. Replace the existing code with the following
code:
Imports System.Web.Services
<WebService(Namespace := "http://tempuri.org/")> _
Public Class Service1
Inherits System.Web.Services.WebService
#Region " Web Services Designer Generated Code "
Public Sub New()
MyBase.New()
'This call is required by the Web Services Designer.
InitializeComponent()
'Add your own initialization code after the InitializeComponent() call.
End Sub
'Required by the Web Services Designer.
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Web Services Designer.
'It can be modified by using the Web Services Designer.
'Do not modify it by using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
components = New System.ComponentModel.Container()
End Sub
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
'CODEGEN: This procedure is required by the Web Services Designer.
'Do not modify it using the code editor.
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#End Region
<WebMethod(EnableSession:=True)> Public Function SetTime(ByVal CurrentTime As String) As String
Session.Add("Time", CurrentTime)
Return (CType(Session("Time"), String))
End Function
<WebMethod(EnableSession:=True)> Public Function GetTime() As String
Return (CType(Session("Time"), String))
End Function
End Class
- On the Build menu, click Build
Solution.
back to the
topCreate an ASP.NET Client Application
When the Web Service method uses a session state, a cookie is
passed back in the response headers to the Web service client. The cookie
uniquely identifies the session for that Web service client. To receive that
cookie for the Web service client, a new instance of
CookieContainer must be created and then assigned to the
CookieContainer property before the Web Service method is called. This makes sure
that the cookie is correctly included in subsequent requests. You must store
the cookies that are received in the session state for future retrieval by this
session. To do this, follow these steps:
- Create a new ASP.NET Web Application by using Visual Basic
.NET.
- Name the project CookieContainerApp.
By default, WebForm1.aspx is created. - In Design view, right-click
WebForm1 and then click View HTML Source.
Replace the existing code with the following code:
<%@ Page language="vb" Codebehind="WebForm1.aspx.vb" AutoEventWireup="false" Inherits="CookieContainerApp.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
<meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 270px; POSITION: absolute; TOP: 143px" runat="server" Text="SetTimeInSession" Width="187px"></asp:Button>
<asp:Button id="Button2" style="Z-INDEX: 102; LEFT: 269px; POSITION: absolute; TOP: 203px" runat="server" Text="GetTimeFromSession"></asp:Button>
<asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 565px; POSITION: absolute; TOP: 150px" runat="server"></asp:Label>
<asp:Label id="Label2" style="Z-INDEX: 104; LEFT: 565px; POSITION: absolute; TOP: 211px" runat="server"></asp:Label>
</form>
</body>
</HTML>
- In Solution Explorer, right-click
References and then click Add Web
Reference.
- In the Address text box, type the
following URL for WebService1:
http://localhost/MyWebService/Service1.asmx
- Click Go and then click Add
Reference.
- In Solution Explorer, right-click
WebForm1.aspx and then click View
Code.
- Replace the existing code in WebForm1
with the following code:
Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents Button1 As System.Web.UI.WebControls.Button
Protected WithEvents Button2 As System.Web.UI.WebControls.Button
Protected WithEvents Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
#Region " Web Form Designer Generated Code "
'This call is required by the Web Form Designer.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
End Sub
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
'CODEGEN: This method call is required by the Web Form Designer.
'Do not modify it using the code editor.
InitializeComponent()
End Sub
#End Region
'Create a new instance of a proxy class for your Web service.
'private localhost.Service1 objWSFunc = new localhost.Service1()
Dim objWSFunc As New localhost.Service1()
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cookieJar As New System.Net.CookieContainer()
' Assign the CookieContainer to the proxy class.
objWSFunc.CookieContainer = cookieJar
' Get CurrentTime
Dim dt As DateTime = DateTime.Now
Dim CurrentTime As String = dt.ToString("s")
' Invoke a Web Service method that uses session state and therefore cookies.
objWSFunc.SetTime(CurrentTime)
' Store the cookies received in the session state for future retrieval by this session.
Session.Add("Time", cookieJar)
Label1.Text = "Time Set in Session : " + CurrentTime
Label2.Visible = False
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
' Get the SessionObject
objWSFunc.CookieContainer = CType(Session("Time"), System.Net.CookieContainer)
Label2.Visible = True
' Call the WebService method to get session state.
Label2.Text = "Time Get from Session : " + objWSFunc.GetTime()
End Sub
End Class
- On the Build menu, click Build
Solution.
back to the
topAdd Content to a Session Object by Using CookieContainer
- On the Debug menu, click
Start to build and to run the Application.
- Click SetTimeInSession.
The
current time value is stored in a session object and this permits the current
time value to display.
In the Button Click Event method, the CookieContainer object is created and then the object is assigned to the CookieContainer property of the Web service proxy class. Then the Web Service
method, SetTime(), is called to update the session object.
back to the
topGet Content from a Session Object by Using CookieContainer
Click
GetTimeFromSession. You may notice that the
time value that is stored in a session object appears when you call the Web
Service method
GetTime().
back to the
top