Microsoft KB Archive/816637

= HOW TO: Use CookieContainer to Maintain a State in Web Services When You Use Visual C# .NET =

Article ID: 816637

Article Last Modified on 5/16/2007

-

APPLIES TO


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

-



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 the Session Object by Using CookieContainer
 * REFERENCES



SUMMARY
This step-by-step article describes how to use the System.Net.CookieContainer class when you use sessions or cookies for 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 a 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 C# .NET.

By default, Service1.asmx is created.
 * 1) Name the project WebService1.
 * 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. To do this, follow these steps:   In Solution Explorer, right-click Service1.asmx and then replace the existing code with the following code: using System; using System.ComponentModel; using System.Web; using System.Web.Services;

namespace WebService1 {   ///     /// Summary description for Service1. ///    public class Service1 : System.Web.Services.WebService {       public Service1 {           //CODEGEN:  Call required by ASP.NET Web Services Designer. InitializeComponent; }

#region Component Designer generated code private void InitializeComponent {       }

#endregion

[WebMethod(EnableSession=true)] public string SetTime(string CurrentTime) {        Session.Add(&quot;Time&quot;, CurrentTime); return ((string) Session[&quot;Time&quot;] ); }

[WebMethod(EnableSession=true)] public string GetTime {        return ((string) Session[&quot;Time&quot;] ); } } } You may notice that the [WebMethod(EnableSession=true)] attribute is added for both Web methods to enable session support.  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 to the Web service client in the response headers. That 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 do this because 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 C# .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=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;CookieContainerApp.WebForm1&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; >   WebForm1 <meta name=&quot;GENERATOR&quot; Content=&quot;Microsoft Visual Studio 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&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/WebService1/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: using System; using System.Web.UI.WebControls;

namespace CookieContainerApp {   ///     /// Summary description for WebForm1. ///    public class WebForm1 : System.Web.UI.Page {     protected System.Web.UI.WebControls.Button Button1; protected System.Web.UI.WebControls.Button Button2; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Label Label2;

// Create a new instance of a proxy class for your Web service. private localhost.Service1 objWSFunc = new localhost.Service1;

private void Page_Load(object sender, System.EventArgs e)       { // Put user code to initialize the page here. }

#region Web Form Designer generated code override protected void OnInit(EventArgs e)       { //           // CODEGEN:  Call required by ASP.NET Web Form Designer. //           InitializeComponent; base.OnInit(e); }       ///         /// Required method for Designer support. Do not modify. /// The contents of this method with the code editor. ///        private void InitializeComponent {            this.Button1.Click += new System.EventHandler(this.Button1_Click); this.Button2.Click += new System.EventHandler(this.Button2_Click); this.Load += new System.EventHandler(this.Page_Load);

}       #endregion

private void Button1_Click(object sender, System.EventArgs e)     { System.Net.CookieContainer cookieJar = new System.Net.CookieContainer; // Assign the CookieContainer to the proxy class. objWSFunc.CookieContainer = cookieJar;

// Get CurrentTime. DateTime dt = DateTime.Now; string CurrentTime = 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;

}

private void Button2_Click(object sender, System.EventArgs e)     { // Get the SessionObject. objWSFunc.CookieContainer = (System.Net.CookieContainer) Session[&quot;Time&quot;];

Label2.Visible=true; // Call the WebService method to access the session state. Label2.Text = &quot;Time Get from Session : &quot;+ objWSFunc.GetTime; }      } } </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 the session object, and the current time appears.

In the button click event, the CookieContainer object is created and then is assigned to the Web service proxy CookieContainer property. Then the Web Service method SetTime is called to update the session object.

back to the top

Get Content from the Session Object by Using CookieContainer
Click GetTimeFromSession. You may notice that the time value that is stored in the session object appears when you call the Web service method GetTime.

back to the top

<div class="references_section">