Microsoft KB Archive/820528

= HOW TO: Use CookieContainer to Maintain a State in Web Services Using Visual Basic .NET =

Article ID: 820528

Article Last Modified on 5/16/2007

-

APPLIES TO


 * Microsoft Web Services Enhancements for Microsoft .NET 1.1
 * Microsoft Web Services Enhancements for Microsoft .NET 2.0
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Visual Basic .NET 2003 Standard Edition

-



This article refers to the following Microsoft .NET Framework Class Libraries:
 * System.Net
 * System.Net.CookieContainer

IN THIS TASK

 * SUMMARY
 * Create a Web Service Application
 * Enable Session Support on the Server
 * Create an ASP.NET Client Application
 * Add Content to a Session Object by Using CookieContainer
 * Get Content from a Session Object by Using CookieContainer
 * REFERENCES



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 top

Create a Web Service Application

 * 1) Run Microsoft Visual Studio .NET. Create a new ASP.NET Web service project by using Visual Basic .NET.

By default, Service1.asmx is created.
 * 1) Name the project MyWebService.
 * 2) On the Build menu, click Build Solution.

back to the top

Enable 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

 _ Public Class Service1 Inherits System.Web.Services.WebService


 * 1) Region &quot; Web Services Designer Generated Code &quot;

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.  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


 * 1) End Region

 Public Function SetTime(ByVal CurrentTime As String) As String Session.Add(&quot;Time&quot;, CurrentTime) Return (CType(Session(&quot;Time&quot;), String)) End Function

 Public Function GetTime As String Return (CType(Session(&quot;Time&quot;), String)) End Function

End Class  On the Build menu, click Build Solution.

back to the top

Create 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.</li>  In Design view, right-click WebForm1 and then click View HTML Source. Replace the existing code with the following code: <%@ Page language=&quot;vb&quot; Codebehind=&quot;WebForm1.aspx.vb&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;CookieContainerApp.WebForm1&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; > <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; content=&quot;Microsoft Visual Studio.NET 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; content=&quot;Visual Basic 7.0&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;> <asp:Button id=&quot;Button1&quot; style=&quot;Z-INDEX: 101; LEFT: 270px; POSITION: absolute; TOP: 143px&quot; runat=&quot;server&quot; Text=&quot;SetTimeInSession&quot; Width=&quot;187px&quot;></asp:Button> <asp:Button id=&quot;Button2&quot; style=&quot;Z-INDEX: 102; LEFT: 269px; POSITION: absolute; TOP: 203px&quot; runat=&quot;server&quot; Text=&quot;GetTimeFromSession&quot;></asp:Button> <asp:Label id=&quot;Label1&quot; style=&quot;Z-INDEX: 103; LEFT: 565px; POSITION: absolute; TOP: 150px&quot; runat=&quot;server&quot;></asp:Label> <asp:Label id=&quot;Label2&quot; style=&quot;Z-INDEX: 104; LEFT: 565px; POSITION: absolute; TOP: 211px&quot; runat=&quot;server&quot;></asp:Label> </HTML> </li> In Solution Explorer, right-click References and then click Add Web Reference.</li> In the Address text box, type the following URL for WebService1:

http://localhost/MyWebService/Service1.asmx

</li> Click Go and then click Add Reference.</li> In Solution Explorer, right-click WebForm1.aspx and then click View Code.</li>  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


 * 1) Region &quot; Web Form Designer Generated Code &quot;

'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

'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
 * 1) End Region

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(&quot;s&quot;)

'         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(&quot;Time&quot;, cookieJar)

Label1.Text = &quot;Time Set in Session : &quot; + 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(&quot;Time&quot;), System.Net.CookieContainer)

Label2.Visible = True '         Call the WebService method to get session state. Label2.Text = &quot;Time Get from Session : &quot; + objWSFunc.GetTime

End Sub End Class </li> On the Build menu, click Build Solution.</li></ol>

back to the top

Add Content to a Session Object by Using CookieContainer

 * 1) On the Debug menu, click Start to build and to run the Application.
 * 2) 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 top

=== Get 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

<div class="references_section">